将数据从Excel导入Word中的组合框
我正在尝试将Excel工作表列中的值添加到使用VBA在Word documnet中创建的用户表单中的组合框中 如果它只是excel用户表单中的一个组合框,那么我需要写的就是:将数据从Excel导入Word中的组合框,excel,vba,ms-word,Excel,Vba,Ms Word,我正在尝试将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文件中获取数据
Range("A1").Select
Do Until Selection.Value = Empty
ComboBox1.AddItem Selection.Value
Selection.Offset(1, 0).Select
Loop
当我在Word中使用用户表单并希望从外部Excel文件中获取数据时,如何执行相同的操作?下面的示例将允许您打开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对象()
另请参见此处的示例: