编辑VBA来扫描文档并挑选出与字符串相对应的参考数字,例如在文档中输出“dog 102”的“102”

问题描述 投票:0回答:1

当文档中字符串的所有实例都附有关联的数字时,我当前执行此操作的代码有效。然而,如果“dog”的某些实例后面没有跟随“102”,而有些实例则跟随“102”,则代码无法返回“102”,即不拾取参考数字,而是得出找不到数字的结论。这是我的代码:

Sub FindRefNumeral()
Dim targetString As String
Dim foundRange As Range
Dim numeral As String

' Get user input
targetString = InputBox("Feature:")

' Search the document
Set foundRange = ActiveDocument.Content
With foundRange.Find
    .text = targetString & " [0-9]{1,3}" & "[A-Za-z]*"
    .MatchWildcards = True
    If .Execute Then
        ' Extract the numeral
        numeral = Split(foundRange.text, " ")(UBound(Split(foundRange.text, " ")))
        MsgBox "Reference numeral: " & numeral
    Else
        MsgBox "No reference numeral found."
    End If
End With
End Sub

我希望宏扫描文档中与参考数字关联的该字符串(即“dog”)的任何实例,并在文本框中输出与该字符串关联的参考数字,即“102”。我还希望宏对文档中的错误数字具有鲁棒性,即如果同时存在“dog 102”和“dog 103”,我希望宏输出最常跟在字符串后面的数字 - 因为这是可能是正确的。

(仅当没有数字与该字符串关联时,即在参考数字之前没有找到所请求字符串的实例,我是否希望输出文本框显示“无数字”。)

这似乎应该是一个简单的修复,大概涉及循环遍历文档中字符串的所有实例,这是代码尚不具备的功能。有什么想法吗?

vba ms-word reference find
1个回答
0
投票
我猜问题出在您搜索词的

"[A-Za-z]*"

 部分。 word 的 find 实现不使用正则表达式,并且 
[A-Za-z]*
 不会查找零个或一个字符,而是查找恰好一个字符。因此,会找到 
dog 123a
,而不会找到 
dog 456

我已将您的例程重写为用于测试的函数:

Function FindRefNumeral(range As range, targetstring As String) As String Dim foundRange As range With range.Find .Text = targetstring & " [0-9]{1;3}" & "[A-Za-z]*" .MatchWildcards = True .Wrap = wdFindContinue Dim okay As Boolean okay = .Execute If okay Then Dim tokens() As String tokens = Split(range.Text, " ") FindRefNumeral = tokens(UBound(tokens)) End If End With End Function
我的测试例程如下所示:

Sub test() Debug.Print FindRefNumeral(ActiveDocument.Content, "dog") Debug.Print FindRefNumeral(ActiveDocument.Content, "cat") End Sub
我正在使用精彩的文字

Header No dog and no cat Hello dog 999 how are you? My cat 23a is great Some more data, another cat and a tiny dog.
结果是

dog: cat: 23a
所以找不到狗的号码。

现在我不知道Word中是否有任何聪明的方法来查找零个或一个字符 - 使用 {0,1} 失败(“无效的搜索词”)。所以我决定首先寻找一个带有

字符的数字,如果失败,则寻找一个“不带”字符的数字: Function FindRefNumeral(range As range, targetstring As String) As String Dim foundRange As range With range.Find .Text = targetstring & " [0-9]{1;3}" & "[A-Za-z]*" .MatchWildcards = True .Wrap = wdFindContinue Dim okay As Boolean okay = .Execute If Not okay Then .Text = targetstring & " [0-9]{1;3}" okay = .Execute End If If okay Then Dim tokens() As String tokens = Split(range.Text, " ") FindRefNumeral = tokens(UBound(tokens)) End If End With End Function

现在的结果正如预期的那样:

dog: 999 cat: 23a

© www.soinside.com 2019 - 2024. All rights reserved.