Userforms and VBA in Word 2007/2010 - Combobox with addresses

Anonymous
2012-02-09T23:44:33+00:00

Hello,

I've been trying to get used to working with User forms, and I've gone as far as being able to create a form, but I am uncertain how to code it to work with a template.  I'm still waiting for some books to come in that I ordered to help me out, so in the mean time I'm looking for a little assistance from you amazing people :-)

The main thing I'm trying to work on is creating a combobox so that I can have a very long list that will continue to grow as I obtain more contacts.  I wanted to use dropdown form fields but realize I can't exceed 25 items per dropdown field.  I could use several dropdown fields to call the data from another document, but I'd like things to look clean.  So I think a combobox will be a much better option.  I want the combo box to have the names of all my contacts, and once a contact is selected, I want their entire mailing address to appear at the top of my letter template.

So let's say I select 'Option1' in the combo box, I'd like the top of my letter to show something resembling the following:

Recipient Name

Address

City, State/Province

Zip Code/Postal Code

I hope I've explained what I'd like done clearly enough, but if you require further explanation I'd be happy to provide.  If there's a better way to do this I'd be happy to hear it.

Thank you!

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments
Answer accepted by question author
Anonymous
2012-02-10T07:04:41+00:00

The simplest solution, if you have it, is to use Outlook to both store the addresses and provide an address book dialog to insert the addresses where you require them. This is covered at http://www.gmayor.com/Macrobutton.htm.

If you want to list the addresses on a userform you will need a multi-column list box and somewhere to store the addresses - probably a document containing a table or perhaps an Excel worksheet, which can be read into the list box. Take a look at http://gregmaxey.mvps.org/word_tip_pages/Old_Tip_Pages/Populate_UserForm_ListBox.htm.

You can then populate a document variable with the contents of the selected item and use a docvariable field to reproduce the value from the docvariable in the document.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments
Answer accepted by question author
Anonymous
2012-02-16T08:44:29+00:00

Don't use bookmarks with a protected form, use a docvariable field in the document and write the value of the selected item from the list box to the variable. Then the protection becomes irrelevant.

If using a multi-column list box, then you will need to re compile the address from the list box columns in the format you require into the variable. Something like the following. I have set the listbox to display only the first column to avoid clutter.

Insert { DocVariable Address } into the document at the place you want the address to appear.

Option Explicit

Private oVars As Variables

Private oSource As Document

Private oTable As Table

Private oRng As Range

Private strWidth As String

Private i As Long, j As Long, k As Long

Private m As Long, n As Long

Private Sub UserForm_Initialize()

Set oSource = Documents.Open(FileName:="C:\Addresses.doc", _

                             AddToRecentFiles:=False, _

                             Visible:=False)

Set oTable = oSource.Tables(1)

'Get the number of list members (i.e., table rows - 1 if header row is used)

i = oTable.Rows.Count - 1

'Get the number of list member attributes (i.e., table columns)

j = oTable.Columns.Count

'Set the number of columns in the Listbox

With Me.ListBox1

    .ColumnCount = j

    strWidth = .Width - 2

    For k = 2 To j

        strWidth = strWidth & ";" & 0

    Next k

    .ColumnWidths = strWidth

    'Load list members into an array

    ReDim myArray(i, j)

    For n = 0 To j - 1

        For m = 0 To i - 1

            Set oRng = oTable.Cell(m + 2, n + 1).Range

            oRng.End = oRng.End - 1

            myArray(m, n) = oRng.Text

        Next m

    Next n

    'Populate the ListBox using the array

    .list() = myArray

    .ListIndex = 0

End With

'Close the source file

oSource.Close SaveChanges:=wdDoNotSaveChanges

End Sub

Private Sub CommandButton1_Click()

Set oVars = ActiveDocument.Variables

oVars("Address").Value = Me.ListBox1.Column(0) & vbCr & _

                         Me.ListBox1.Column(1) & vbCr & _

                         Me.ListBox1.Column(2) & vbCr & _

                         Me.ListBox1.Column(3)

ActiveDocument.Fields.Update

Unload Me

End Sub

Was this answer helpful?

0 comments No comments

42 additional answers

Sort by: Most helpful
  1. Anonymous
    2012-02-15T15:37:42+00:00

    Graham,

    I believe your suggestion will likely work, I'm still very new to this and it takes me a while to learn anything lol...

    Here is my code so far:

    Option Explicit

    Private Sub UserForm_Initialize()

    Dim myArray() As Variant

    Dim sourcedoc As Document

    Dim i As Integer

    Dim j As Integer

    Dim myitem As Range

    Dim m As Long

    Dim n As Long

    Application.ScreenUpdating = False

    'Modify the following line to point to your list member file and open the document

    Set sourcedoc = Documents.Open(FileName:="C:\Addresses.doc")

    'Get the number of list members (i.e., table rows - 1 if header row is used)

    i = sourcedoc.Tables(1).Rows.Count - 1

    'Get the number of list member attributes (i.e., table columns)

    j = sourcedoc.Tables(1).Columns.Count

    'Set the number of columns in the Listbox

    ListBox1.ColumnCount = j

    'Load list members into an array

    ReDim myArray(i, j)

    For n = 0 To j - 1

      For m = 0 To i - 1

        Set myitem = sourcedoc.Tables(1).Cell(m + 2, n + 1).Range

        myitem.End = myitem.End - 1

        myArray(m, n) = myitem.Text

      Next m

    Next n

    'Populate the ListBox using the array

    ListBox1.List() = myArray

    'Close the source file

    sourcedoc.Close SaveChanges:=wdDoNotSaveChanges

    End Sub

    Private Sub CommandButton1_Click()

    Dim i As Integer

    Dim Address As String

    Dim oRng As Word.Range

    Address = ""

    For i = 1 To ListBox1.ColumnCount

      ListBox1.BoundColumn = 1

      If i < ListBox1.ColumnCount Then

        Address = Address & ListBox1.Value & vbCr

      Else

        Address = Address & ListBox1.Value & vbCr

      End If

    Next i

    Set oRng = ActiveDocument.Bookmarks("Address").Range

    oRng.Text = Address

    ActiveDocument.Bookmarks.Add "Address", oRng

    Me.Hide

    End Sub

    I can get the listbox to call the table I have created with all the addresses I'd like to use in my template, but I can't seem to get it to properly display without an error.  I'd also like it to display in the template as the following format:

    Name

    Address

    City, State/Province

    Zip/Postal Code

    So my table looks like the below:

    Column1                  Column2                  Column3                  Column4                  

    Test1                         Address                   City, State/Prov        Zip/Postal Code

    Test2                         Address                   City, State/Prov        Zip/Postal Code

    Test3                         Address                   City, State/Prov        Zip/Postal Code

    Test4                         Address                   City, State/Prov        Zip/Postal Code

    So let's say I click the command button after selecting the row containing Test1, it returns this:

    Test1

    Test1

    Test1

    Test1

    Is there something in my code that needs to be fixed to return this?:

    Test1

    Address

    City, State/Prov

    Zip/Postal Code

    Also, this is why I was asking for an unprotect and re-protect method because the example on the webpage you suggested says to insert with bookmarks and I am asked to debug if the form is protected when clicking the command button.

    Thanks!

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2012-02-15T06:45:49+00:00

    If you assign the value from the userform field to a docvariable and use a docvariable field to display the result rather than a form field, then there is no need to unprotect the form. The field will update to display the data e.g.

    Dim oVars As Variables

    Dim oFld As Field

    Set oVars = ActiveDocument.Variables

    oVars("VariableName").Value = "This is the value you want to display"

    For Each oFld In ActiveDocument.Fields

        If oFld.Type = wdFieldDocVariable Then oFld.Update

    Next oFld

    Was this answer helpful?

    0 comments No comments
  3. Charles Kenyon 171.2K Reputation points Volunteer Moderator
    2012-02-14T22:12:40+00:00

    I don't have time to parse it right now. What follows is from a module to unprotect a protected form that has a password stored in a document variable, make changes, and reprotect it.

    Option Explicit

    Public sPass As String

    ' Module and Project Written by Charles Kyle Kenyon

    ' May 2001, Copyright 2001 All rights reserved

    Sub DucesTecum()

    '

    ' DucesTecum Macro

    ' OnExit macro for DucesTecum Checkbox

    ' "&chr(10)&"Macro recorded 05/16/2001 by Charles Kyle Kenyon

    '

        Dim strBringWith As String, rRange As Range

        With ActiveDocument

            UnProtectSubpoena  'subroutine below

            Set rRange = .Bookmarks("YouBringYes").Range

            'Save result of form field

            strBringWith = .FormFields("BringWhat").Result

            If .FormFields("chkDucesTecum").CheckBox.Value _

                = True Then

                .FormFields("DucesTecumTitle").TextInput.EditType _

                    Type:=wdRegularText, Default:=" Duces Tecum "

                If strBringWith = "" Then strBringWith = _

                    "Bring what?" 'End If

                .FormFields("BringWhat").TextInput.EditType _

                    Type:=wdRegularText, Default:=strBringWith, _

                        Enabled:=True

                rRange.Font.DoubleStrikeThrough = False

                rRange.Font.Bold = True

                .FormFields("BringWhat").Select

            Else

                .FormFields("DucesTecumTitle").TextInput.EditType _

                    Type:=wdRegularText, Default:=" ", Enabled:=False

                .FormFields("BringWhat").TextInput.EditType _

                    Type:=wdRegularText, Default:="", Enabled:=False

                rRange.Font.DoubleStrikeThrough = True

                rRange.Font.Bold = False

                .FormFields("chkThirdParty").Select

            End If

            .Protect wdAllowOnlyFormFields, True, sPass

        End With

    End Sub

    Sub ThirdParty()

    '

    ' ThirdParty Macro

    ' OnExit Macro for Third-Party Checkbox

    ' "&chr(10)&"Macro written 05/16/2001 by Charles Kyle Kenyon

    '

        Dim rRange As Range

        With ActiveDocument

            UnProtectSubpoena 'subroutine below

            Set rRange = .Bookmarks("ThirdPartyLanguage").Range

            rRange.Font.DoubleStrikeThrough = _

                Not .FormFields("chkThirdParty").CheckBox.Value

            rRange.Font.Bold = _

                .FormFields("chkThirdParty").CheckBox.Value

            .Protect wdAllowOnlyFormFields, True, sPass

        End With

    End Sub

    Private Sub UnProtectSubpoena() 'Subroutine for other procedures

        With ActiveDocument

            sPass = .Variables("FormPassWord")

            If .ProtectionType <> wdNoProtection Then .Unprotect (sPass)

            ' End If

        End With

    End Sub


    End of module. Hope this is useful to you.

    Was this answer helpful?

    0 comments No comments