【问题标题】:Find string in doc using wildcards; return full string VBA使用通配符在文档中查找字符串;返回完整的字符串 VBA
【发布时间】:2013-10-15 08:04:40
【问题描述】:

我需要做的是在 word 文档中搜索美元金额,然后将金额返回给程序以供用户验证。我知道金额以“$”开头,并以小数点后两位数结尾(每个文档只有一个金额)。搜索结果如我所愿,但我实际上如何从 word 文档中提取完整的数字(分配给变量)

以下代码(Excel 2010);干杯。

With wdDoc.Content.Find
   .Text = "$*.??"
   .MatchWildcards = True
   If .Execute Then
      'would be verified here
   Else
      'etc
   End If
End With

编辑: 我设法使以下工作;

   With wdApp.Selection.Find
      .Text = "$*.??"
      .Wrap = wdFindAsk
      .Forward = True
      .MatchWildcards = True
      If .Execute Then
         debug.print wdApp.Selection.Text
      Else
         debug.print "Not Found"
      End If
   End With

唯一的负面影响是,如果用户在搜索运行时设法选择了不同的 word 文档,它将找不到结果,因为选择已更改。有没有办法专门搜索代码中之前打开的活动文档? (“wdDoc”)。使用 wdDoc.Content 似乎没有任何返回字符串的方法。

Edit2:有没有办法使用 Word.Document 而不是 Word.Application 从搜索中返回文本?

【问题讨论】:

    标签: excel search ms-word vba


    【解决方案1】:

    试试这个

    With ActiveDocument.Content.Find
        .Text = "$*.??"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .MatchWildcards = True
        If .Execute Then
            Debug.Print Selection.Range.Text
        Else
            Debug.Print "not Found"
        End If
    End With
    

    跟进

    试试这个(尝试和测试)

    Sub Sample()
        ActiveDocument.Content.Select
        With Selection.Find
            .Text = "$*.??"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .MatchWildcards = True
            If .Execute Then
                Debug.Print Selection.Range.Text
            Else
                Debug.Print "not Found"
            End If
        End With
    End Sub
    

    【讨论】:

    • 使用 Selection.Range.Text 会出现错误“450:参数数量错误或属性分配无效”
    【解决方案2】:

    您可以使用Range 对象来引用找到的文本。

    此外,如果存在流浪 $,则查找模式 $*.?? 可以在您的文档中找到许多内容,而不是您想要的内容。

    您可以使用此模式精确找到美元金额

    $[0-9]{1,}.[0-9]{2}
    

    Sub Demo()
        Dim wdDoc As Document
        Dim oRng As Range
    
        ' Set reference to required doc
        Set wdDoc = ActiveDocument
    
        ' ....
    
        Set oRng = wdDoc.Content
        With oRng.Find
            .Text = "$[0-9]{1,}.[0-9]{2}"
            .Wrap = wdFindAsk
            .Forward = True
            .MatchWildcards = True
    
            If .Execute Then
               Debug.Print oRng
            Else
              'etc
            End If
        End With
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      相关资源
      最近更新 更多