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

时间:2016-07-12 17:06:50

标签: excel vba ms-word word-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

1 个答案:

答案 0 :(得分: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范围表示,并且您需要设置范围的文本,例如

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

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