0

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

我打开宏并有以下代码

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

4

1 回答 1

1

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

对于您在评论中发布的问题,要更新Control的实际内容而不是标题,您需要知道内容是由Word Range表示的,并且您需要设置范围的文本,例如

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

您仍然需要遍历控件集合。

于 2016-07-13T19:36:38.037 回答