Microsoft Word VBA - Select table if cell contains specified string

梦想的初衷 提交于 2019-12-25 16:55:03

问题


I'm having trouble creating a Microsoft-Word macro. Here's the macro that I'm working on. It successfully selects each individual table in a word document.

Sub FindSpecificTables()
    Selection.WholeStory

    Dim iResponse As Integer
    Dim tTable As Table

    'If any tables exist, loop through each table in collection.
    For Each tTable In ActiveDocument.Tables
        tTable.Select
        If response = vbNo Then Exit For 'User chose to leave search.
    Next
    MsgBox prompt:="Search Complete.", buttons:=vbInformation
End Sub

However, I only need to select a table if the table contains a specified string. This should be simple enough, but I can't figure it out. How can I search a table for a specific string?

I've tried adjusting the code with the following conditional statement:
If tTable.Cell(1, 1) = "Adjusted:" Then tTable.Select; see example below.

Sub FindSpecificTables()
    Selection.WholeStory

    Dim iResponse As Integer
    Dim tTable As Table
    'If any tables exist, loop through each table in collection.
    For Each tTable In ActiveDocument.Tables
        If tTable.Cell(1, 1) = "MySpecifiedString:" Then tTable.Select
        If response = vbNo Then Exit For 'User chose to leave search.
    Next
    MsgBox prompt:="Search Complete.", buttons:=vbInformation
End Sub

Unfortunately, this isn't working. Is my syntax wrong? Do you guys have any suggestions or recommendations?


回答1:


Try with different approach... instead of looping each table loop search (find) method and check if text found is within table. here is simple solution:

Sub Find_Text_in_table()

    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "donec"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

    Do While Selection.Find.Execute

        If Selection.Information(wdWithInTable) Then

            Stop
            'now you are in table with text you searched
            'be careful with changing Selection Object
            'do what you need here
        End If
    Loop
End Sub


来源:https://stackoverflow.com/questions/31656792/microsoft-word-vba-select-table-if-cell-contains-specified-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!