Home > Software design >  VBA: search bookmarks with Regex
VBA: search bookmarks with Regex

Time:02-19

I have a lot of bookmarked tables in MS Word, named "step", "step1", "step_01", etc. What I need from VBA, is to select all of those tables by bookmarks, and I have to use Regex for this. The thing is, that I managed only to select the "step" table. How can I use Regex in here correctly? My code:

    Function GetTable(sTableName As String) As Table
    On Error Resume Next
    Set GetTable = ActiveDocument.Bookmarks(sTableName).Range.Tables(1)
End Function

Sub TestTableWithName()
    Dim myTable As Table
    Dim regexObject As RegExp
    Set regexObject = New RegExp
    With regexObject
        .Pattern = "step\w"
        .Global = True
        .IgnoreCase = True
    End With
    Set myTable = GetTable("step")
    If Not myTable Is Nothing Then
        myTable.Range.Select
    End If
End Sub

CodePudding user response:

For example:

Sub FindBookmarkedTables()
    Dim bmk As Bookmark, myTable As Table
    For Each bmk In ActiveDocument.Bookmarks
        If Left(bmk.Name, 4) = "step" Then Set myTable = bmk.Range.Tables(1)
    Next bmk
End Sub

CodePudding user response:

You don't say how the bookmark has been applied. This response assumes that the bookmark range encompasses the Table range.

The function GetTables returns a collection of all Tables that have a bookmark which includes the text ipBookMarkText

Public Sub Test()

    
    Dim myColl As Collection
    Set myColl = GetTables("Step")
    
End Sub

Public Function GetTables(ByVal ipBookmarkText As String) As Collection

    Dim myTables As Collection
    Set myTables = New Collection
    
    Dim myTable As Table
    
    For Each myTable In ActiveDocument.Tables
    
        Debug.Print myTable.Range.Tables.Item(1).Range.Bookmarks.Item(1).Name
        If InStr(LCase$(myTable.Range.Tables.Item(1).Range.Bookmarks.Item(1).Name), LCase$(ipBookmarkText)) Then
        
            myTables.Add myTable
            
        End If
        
    Next

    Set GetTables = myTables

End Function

If you DO need to use regex for some unfathomable reason, then use the string obtained by the '.Name' method as the source string for the regex.

  • Related