0

我试图找出我的书签在我的 Word 文档中的哪个表格单元格。我循环浏览书签没有问题,这很简单。现在,我正在尝试识别书签所在的表格单元格,但我很难做到这一点。

或者,有没有办法将数据绑定到书签(例如使用封闭的书签),然后可以引用并复制到另一个文档?我不能使用封闭的书签,因为单元格中的文本需要经常更改,并且用户不希望每次都为新文本添加书签。

4

3 回答 3

1

我使用了此链接中提供的 RowIndex 和 ColumnIndex -

Word VBA - 如何找到包含内容控件的表格单元格?

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)
于 2018-10-09T06:11:51.717 回答
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
于 2012-09-11T19:19:01.927 回答
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

显然,可以实现通过书签的循环来执行多个测试。这应该比测试每个表格/单元格更有效。

于 2018-10-09T07:16:58.643 回答