如何将Excel数据导入Word的ContentControl
我在文档上放置了纯文本内容控件。
我打开macros并有以下代码
Sub PrefillDocument() ' ' PrefillDocument Macro ' ' Dim docName As ContentControls Dim objExcel As Object Dim FileName As String FileName = ActiveDocument.Path & "\CountyData.xlsx" Set objExcel = CreateObject("Excel.Application") Set exWb = objExcel.Workbooks.Open(FileName) MsgBox exWb.Sheets("4").Cells(1, 2) // Works ' Having problems trying to get the data from Excel into the content control Set docName = ActiveDocument.SelectContentControlsByTag("Name") // Get docName.Item.Title = exWb.Sheets("4").Cells(1, 2) MsgBox docName.Title 'ActiveDocument.FormFields("Name").Result = 'ThisDocument.m_name.Caption = exWb.Sheets("Member's Data").Cells(2, 1) exWb.Close Set exWb = Nothing End Sub
我被告知不要使用任何遗留控件,所以我不得不使用新的ContentControls
docName是控件的集合,在这种情况下,Word不会让您将标题应用于集合中的每个控件。
所以你将需要迭代,例如
Dim cc as ContentControl For Each cc In docName cc.Title = exWb.Sheets("4").Cells(1, 2) Next
或者你可能会放弃你的docName声明,并做
Dim cc as ContentControl For Each cc In ActiveDocument.SelectContentControlsByTag("Name") cc.Title = exWb.Sheets("4").Cells(1, 2) Next
对于在注释中发布的问题,要更新控件的实际内容而不是标题,需要知道内容是由Word范围表示的,并且需要设置范围的文本,例如
cc.Range.Text = exWb.Sheets("4").Cells(1.2)
您仍然需要遍历控件的集合。