在 Word 文档中存储多个位置

Store several places in a Word document

提问人:Loveb 提问时间:11/14/2023 更新时间:11/14/2023 访问量:47

问:

我希望我有一个简单的问题。我简化了下面的代码,它需要在两个不同的场合运行。可能吗,我该怎么做?这些文件通常大于 200 页。

Sub findAndStore()
Dim pgf As Paragraph
For Each pgf In ActiveDocument.Paragraphs
    If pgf.Range.text = "[table]" & vbCr Then
        'store place in document
    End If
Next
End Sub

Sub addTables()
for each stored place in document do
    Call AddTable("place in document")
Loop
End Sub
VBA MS-Word

评论

0赞 Loveb 11/14/2023
第二部分应自下而上运行,以免破坏文档中保存的位置。
0赞 Red Hare 11/14/2023
我会使用书签(如果无法直接插入找到的位置),例如 myBo + 计数器。在找到的范围周围设置书签。然后从myBo开始进行书签检查,然后插入表格并删除书签。

答:

2赞 Tim Williams 11/14/2023 #1

您可以尝试如下操作:

Option Explicit

Dim col As Collection 'global to store ranges

Sub findAndStore()
    Dim pgf As Paragraph
    Set col = New Collection
    For Each pgf In ActiveDocument.Paragraphs
        If pgf.Range.Text = "[table]" & vbCr Then
            col.Add pgf.Range.Duplicate 'store a copy of `rng`
        End If
    Next
End Sub

Sub addTables()
    Dim rng As Range
    For Each rng In col 'loop through saved ranges
        AddTable rng
    Next rng
End Sub

'dummy sub
Sub AddTable(rng As Range)
    ActiveDocument.Tables.Add rng, 2, 5
End Sub


1赞 taller 11/14/2023 #2
  • 利用书签标记位置,然后在插入表格后删除书签。
  • 书签存储在文档中,确保即使在重新打开文档时也能保留书签。
Option Explicit

Sub findAndStore()
    Dim pgf As Paragraph
    Dim iIndex As Long
    For Each pgf In ActiveDocument.Paragraphs
        If pgf.Range.Text = "[table]" & vbCr Then
            ' Insert Bookmark
            With ActiveDocument.Bookmarks
                .Add Range:=pgf.Range, Name:="TableBK" & iIndex
                .DefaultSorting = wdSortByName
                .ShowHidden = False
            End With
            iIndex = iIndex + 1
        End If
    Next
End Sub

Sub addTables()
    Dim oBK As Bookmark
    ' Loop through bookmark and insert table
    For Each oBK In ActiveDocument.Bookmarks
        Call AddTable(oBK.Range)
        oBK.Delete
    Next
End Sub

' Add table next to [table]
Sub AddTable(BKRng As Range)
    Dim tabRng As Range
    Set tabRng = ActiveDocument.Range(BKRng.End, BKRng.End)
    ActiveDocument.Tables.Add Range:=tabRng, _
         NumRows:=2, NumColumns:=2, _
         DefaultTableBehavior:=wdWord9TableBehavior, _
         AutoFitBehavior:=wdAutoFitFixed
End Sub

评论

0赞 Loveb 11/14/2023
感谢红兔和更高,您的建议与持久的解决方案更好。