简体   繁体   中英

Populate Word Combobox with Excel data through VBA

I'm new to VBA, so I'm struggling with this for a couple of days now.

I have a combobox in Word with contacts, I also have an excel file(contacts.xls) with one column (names of the all the contacts). When I open the Word-document the Macro has to fill in the combobox with all the names from the excel file.

Is it possible to send me a working example of this for word 2007? Seems quite simple, but just can't get this to work...

Thanks in advance!

If you intend on reading from an Excel file in Word you are going to have to open it. It will use code like this:

   Dim oExcel As Object
   Dim oBook As Object
   Dim oSheet As Object

   'Start a new workbook in Excel
   Set oExcel = CreateObject("Excel.Application")
   Set oBook = oExcel.Workbooks.Open("FileName.xlsx")

You will also probably want to go to Tools->References in the VB project and find whatever Excel library is on your machine (and check it of course). There are ways around this if needed, but it is easier.

You then can read the values from the workbook:

oBook.Worksheets(1).cells(1,1)

I'm not totally sure what the syntax to get it into the combo box is. Look up "combobox object members" in the vbe in word. There will be a list property, or something like that.

Sorry, I'm on a linux machine right now, so I can't debug exact code for you.

I have more full code for you now:

Option Explicit

Sub TestDropDownFromExcel()

    Dim counter As Long
    Dim xlApp As Excel.Application
    Dim xlBook As Workbook
    Dim oCC As ContentControl

    Set oCC = ActiveDocument.ContentControls(1)

    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Open("C:\Path\To\MyFile.xlsx")

    If xlBook Is Nothing Then
        Exit Sub
    End If

    oCC.DropdownListEntries.Clear

    For counter = 1 To 10
        oCC.DropdownListEntries.Add Text:=xlBook.Worksheets(1).Cells(counter, 1), Value:=CStr(counter)
    Next counter

    xlApp.Visible = True

    Set xlBook = Nothing
    Set xlApp = Nothing 

End Sub

Be aware that there is very little error checking going on here. Also, rather than the call to .Visible at the end, you can simply call .Close if you do not want the user to see it (for the final project, this is probably preferable. The deferencing (= Nothing) is good practice to have, but VBA cleans up automatically at the end of execution. Obviously I am assuming tyou want the first dropdown (ContentCOntrols(1)) but this may not be true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM