如何将我的 Excel 数据放入 Word 的 ContentControl

How do I get my Excel data into Word's ContentControl

我在我的文档中放置了一个纯文本内容控件。

我打开了宏,得到了下面的代码

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 是一个 collection 控件,在这种情况下,Word 不会让您将标题应用到 Collection 中的每个控件。

所以你需要迭代,例如

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 Range 表示的,并且您需要将文本设置为范围,例如

cc.Range.Text = exWb.Sheets("4").Cells(1.2)

您仍然需要遍历 collection 控件。