我试图找出我的书签在我的Word文档中的哪个表格单元格。循环书签没有问题,这非常简单。现在,我正在尝试识别书签所在的表格单元格,但是我很难做到这一点。
或者,有没有办法将数据绑定到书签(比如使用随附的书签),然后可以将其引用并复制到另一个文档?我不能使用附带的书签,因为单元格中的文本需要经常更改,用户不希望每次都必须为新文本添加书签。
答案 0 :(得分:0)
如上所述,更好的方法是通过表格查找书签。我的下面的脚本遍历第一个表的第二列,查找所有书签。它找到的书签对应于我在其他文档“Document to Populate.docx”中设置的书签。无论何处找到书签,ActiveDocument中的数据都会填充到第二个文档中,如下所示:
Sub AutomateQuestionnaire2()
' Prototype 2
' Different approach was used, instead of looping through bookmarks, loop
' through the tables looking for bookmarks. This method is more flexible
' and is better suited for our Word documents which always include tables.
' Limitations: Bookmark needs to be in both documents using the same ID, and
' data must be in a table, column 2.
Dim oRow As Row
Dim oRange As Range
Dim oFindRange As Range
Dim oBookmark As Bookmark
Dim oQuestionnaire As Word.Document
Dim oApp As Word.Application
Dim strFilePath As String
Dim strText As String
strFilePath = ActiveDocument.Path
'Open the second to populate it
Set oApp = New Word.Application
oApp.Visible = True
Set oQuestionnaire = oApp.Documents.Open(strFilePath + "\Document to Populate.docx")
'We'll loop through each row of the table looking for bookmarks, if a bookmark is found
'the text adjacent to that bookmark, in the table cell, will be copied to the same
'bookmark if found in the questionnaire.
For Each oRow In ActiveDocument.Tables(1).Rows
'Limits the range to the middle column as is the case for the ITGC 532 form
Set oRange = oRow.Cells(2).Range
Set oBookmark = oRange.Bookmarks(1)
'VBA will terminate the script if it comes across an error, instead
'let's add some error handling to skip errors.
On Error GoTo SkipToNext
strText = oRange.Text
oQuestionnaire.Bookmarks(oBookmark).Range.Text = strText
'Find the newly inputted text and differentiate it (bold for now)
Set oFindRange = oQuestionnaire.Content
oFindRange.Find.Execute FindText:=strText, Forward:=True
If oFindRange.Find.Found = True Then oFindRange.Font.ColorIndex = wdBlue
SkipToNext:
Next
答案 1 :(得分:0)
我使用了此链接中提供的RowIndex和ColumnIndex-
Word VBA - How to locate table cell containing Content Control?
Dim bkRange As Range
Dim rIndex, cIndex As Integer
Set bkRange = ActiveDocument.Bookmarks(bookmarkName).Range
rIndex = bkRange.Cells(1).RowIndex
cIndex = bkRange.Cells(1).ColumnIndex
一旦获得这些值,就可以像-
一样访问表格的单元格ActiveDocument.Tables(1).Cell(rIndex, cIndex)
答案 2 :(得分:0)
不需要遍历表,更不用说它们的行和列了。这是一些非常简单的代码供您使用:
Sub TestBookMark(BkMkNm As String)
Dim Rng As Range
With ActiveDocument
Set Rng = .Range(0, 0)
With .Bookmarks(BkMkNm).Range
If .Information(wdWithInTable) = True Then
Rng.End = .End
MsgBox "Bookmark: " & BkMkNm & vbTab & "Table: " & Rng.Tables.Count & vbTab & "Row: " & .Cells(1).RowIndex & vbTab & "Column: " & .Cells(1).ColumnIndex
End If
End With
End With
End Sub
您可以使用以下代码进行调用:
Sub Demo()
Call TestTable("BkMk")
End Sub
很显然,可以实现遍历书签的循环以执行多个测试。这应该比测试每个表/单元格要有效得多。