您可以使用多种方法将数据写入 Word 中的表格,其中一种基于您已有的:
1.使用 Find.Execute
如果您必须坚持使用模板中带有预定义标签的表格,那么您应该使用Range 对象进行查找,而不是使用Document.Content。这使您可以操作文档中的“目标位置”,类似于使用范围而不是从工作簿级别定位工作簿中的单元格的方式。
Dim rngSearch as Word.Range
Set rngSearch = wrdDoc.Content
rngSearch.Find.Execute FindText:="<PNAME>", ReplaceWith:="<Project Name> " & strProjectName
'Move to next cell
rngSearch.Collapse wdCollapseEnd
rngSearch.Text = "text for the second column"
rngSearch.Find.Execute FindText:="<PID>", ReplaceWith:="<Project ID>=" & strProjectID
'and repeat collapsing, assign text and Find.Execute
代码结构考虑:将 Find/Collapse/Text 步骤放在单独的过程 (Sub) 中可能是有意义的。这样可以省去为每个“标签”重复这三个步骤:
'code in main procedure
Dim rngFind as Word.Range
Set rngFind = wrdDoc.Content
WriteToTagsInWordTable "<PNAME>", "<Project Name> " & strProjectName,
"text in column two", rngFind
WriteToTagsInWordTable "<PID>", "<Project Name>=" & strProjectID,
"other text in column two", rngFind
'and so on...
Sub WriteToTagsInWordTable(sFind as String, sReplace as String, _
sColTwo as String, ByRef rngSearch as Word.Range)
rngSearch.Find.Execute FindText:=sFind, ReplaceWith:=sReplace
'Move to next cell
rngSearch.Collapse wdCollapseEnd
rngSearch.Text = sColTwo
End Sub
2。使用书签
不要在 Word 文档中的字符串标签上使用 Find,而是将标签替换为 书签 并直接在代码中定位书签。这应该更快。您可以为第二列插入额外的书签,或者使用上述技术移动到下一个单元格。
With wrdDoc
.Bookmarks("PName").Range.Text = "<Project Name> " & strProjectName
.Bookmarks("PNameInfo").Range.Text = "text for the second column"
End With
3.在代码中创建表格
生成 in VBA 代码通常是最有效的,作为字符分隔的字符串,然后分配给目标 Range(通常由 Bookmark 表示),并转换为表格。这在我的 MSDN 文章 https://msdn.microsoft.com/en-us/library/aa537149%28v=office.11%29.aspx?f=255&MSPPError=-2147217396 的“使用数据填充单词表”部分中有详细描述。
这是那篇文章中的相关代码。它展示了如何从数组中为多行、多列表构建字符串,将字符串传递给 Word Range 并将其转换为表格。
Sub CreateTableFromString(ByRef rng As Word.Range, _
ByRef adata() As Variant)
Dim tbl As Word.Table
rng.Text = BuildDataString(adata)
Set tbl = rng.ConvertToTable(vbTab, _
AutoFitBehavior:=wdAutoFitFixed, _
DefaultTableBehavior:=wdWord8TableBehavior)
End Sub
Function BuildDataString(aData() As Variant) As String
Dim dataString As String
Dim nrRow As Long, nrCol As Long
For nrRow = 0 To UBound(aData, 1)
For nrCol = 0 To UBound(aData, 2)
dataString = dataString & aData(nrRow, nrCol)
If nrCol < UBound(aData, 2) _
Then dataString = dataString & vbTab
Next nrCol
If nrRow < UBound(aData, 1) _
Then dataString = dataString & vbCr
Next nrRow
BuildDataString = dataString
End Function