将数据从Excel导入Word中的组合框

时间:2013-12-31 14:14:10

标签: excel vba ms-word word-vba

我正在尝试将Excel工作表列中的值添加到我使用VBA在Word documnet中创建的用户表单中的组合框中。

如果它只是excel用户表单中的组合框,那么我需要写的是:

Range("A1").Select
Do Until Selection.Value = Empty
    ComboBox1.AddItem Selection.Value
    Selection.Offset(1, 0).Select
Loop

当我在Word中使用用户表单并想要外部Excel文件中的数据时,如何做同样的事情?

1 个答案:

答案 0 :(得分:0)

以下示例允许您打开Excel文件并浏览所需的范围。它是为了下拉列表但类似的:

Option Explicit

Sub TestDropDownFromExcel()

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

    Set oCC = ActiveDocument.ContentControls(1)

    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Open("...")  'Location of your file
    If xlBook Is Nothing Then
        Exit Sub
    End If

    Set xlSheet = xlBook.Sheets(1)

    'Empty the list of items in the dropdown
    oCC.DropdownListEntries.Clear

    'Populate your items here


    xlApp.Visible = True

    Set xlSheet = Nothing    
    Set xlBook = Nothing
    Set xlApp = Nothing

End Sub

您需要包含对Excel的引用:首先,您需要为Microsoft Excel对象库设置引用(菜单:工具 - >引用),然后您可以访问所有Excel对象(How to refer to Excel objects in Access VBA?

此处还可参见示例:Populate Word Combobox with Excel data through VBA