有許多的方法可以使用將數據寫入到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
代碼結構考慮:將查找/摺疊/文本步驟放在單獨的過程(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.創建表中代碼
它通常是最有效的,以產生在VBA代碼,作爲一個字符分隔的字符串,真實然後分配給目標Range
(通常由Bookmark
表示) ,並轉換爲表格。這在我的MSDN文章https://msdn.microsoft.com/en-us/library/aa537149%28v=office.11%29.aspx?f=255&MSPPError=-2147217396的「使用數據填充Word表格」一節中詳細介紹。
下面是該文章的相關代碼。它演示瞭如何從數組中構建多行多列表的字符串,將字符串傳遞到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
插入點是未知的,請參閱原始代碼,使用查找/替換 – andrewb
我不認爲你可以使用查找/替換選項卡切換到下一個單元格。 – gtwebb
使用.Find.Execute依次查找(而不是替換)每個模板標籤應該是相當簡單的,用適當的替換它,然後將選擇移動到下一列並在該列中插入更多的文本(假設這是OP想要的,因爲它不完全清楚)。你不能做的就是一次性調用.Find.Execute。 –