【问题标题】:Microsoft Word VBA - Select table if cell contains specified stringMicrosoft Word VBA - 如果单元格包含指定的字符串,则选择表格
【发布时间】:2015-07-27 15:12:24
【问题描述】:

我在创建 Microsoft-Word 宏时遇到问题。这是我正在处理的宏。它成功地选择了 word 文档中的每个单独的表。

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

但是,如果表格包含指定的字符串,我只需要选择表格。这应该很简单,但我无法弄清楚。如何在表格中搜索特定字符串?

我尝试使用以下条件语句调整代码:
If tTable.Cell(1, 1) = "Adjusted:" Then tTable.Select; 见下面的例子

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

很遗憾,这不起作用。我的语法错了吗?大家有什么建议或建议吗?

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    尝试不同的方法...而不是循环每个表格循环 search (find) 方法并检查找到的文本是否在表格内。这是一个简单的解决方案:

    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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多