我想在文档中找到如下模式:
1234567 版本:3
数字会改变,但结构保持不变。我想找到该值,并将以下文本分配给将用于命名文档的变量:
1234567-3。
当文档具有以下模式时,我所拥有的和正在工作的内容如下:
1234567-3
现在文档显示该信息为
1234567 版本:3。
您能帮助我使用查找功能并转换为新格式吗?
Sub FindPattern()
Dim regEx As Object
Dim matchCollection As Object
Dim eString As String
Set regEx = CreateObject("VBScript.RegExp")
With regEx
.IgnoreCase = True
.Global = False ' Only look for 1 match; False is actually the default.
.Pattern = "[0-9]{7} - [0-9]{1}" ' Word separates lines with CR (\r)
End With
有三个要求:
- 将文档的文本作为要搜索的文本传递给 regEx.Execute()。
- 为了快速测试此语句,传递“程序:程序名称(abr)”设置 matchCollection = regEx.Execute(ActiveDocument.Content.Text)
提取第一个子匹配项(捕获组)的值 - 例如“程序名称(abr)” - 并将其分配给变量
extractedString
。
此行过去必须estring = matchCollection(0).Submatch(0)
提取第一个匹配项,但我遇到了错误。这是我的代码:eString = matchCollection(0) ' On Error Resume Next ' Dim strName As String, dlgSave As Dialog Set dlgSave = Dialogs(wdDialogFileSaveAs) ' name with date and quote number strName = Format((Month(Now() + 1) Mod 100), "0#") & "_" & _ Format((Day(Now()) Mod 100), "0#") & "_" & _ Format((Year(Now()) Mod 100), "20##") & "_ _" & eString With dlgSave .Name = strName .Show End With End Sub
答案1
Option Explicit
Function FindPattern(myText As String, ByRef result As String) As Boolean
Dim regEx As Object
Dim extract As Variant
Set regEx = CreateObject("VBScript.RegExp")
With regEx
.IgnoreCase = True
.Global = False
'.Pattern = "([0-9]{7}) - ([0-9]{1})" ' Pattern <1234567 - 3>
.Pattern = "([0-9]{7}) Ver:([0-9]{1})" ' Pattern <1234567 Ver:3>
End With
Set extract = regEx.Execute(myText)
If extract.Count = 0 Then
result = ""
FindPattern = False
Else
' Result a la <1234567-3>
result = extract(0).subMatches(0) & "-" & extract(0).subMatches(1)
FindPattern = True
End If
End Function
Sub test_Findpattern()
Dim theText As String
Dim result As Boolean
Dim Sresult As String
theText = "Blabla 1234567 - 3 blabla"
result = FindPattern(theText, Sresult)
Debug.Print 1, result, Sresult
theText = "Blabla 1234567 Ver:3 blabla"
result = FindPattern(theText, Sresult)
Debug.Print 2, result, Sresult
theText = Application.ActiveDocument.Range
result = FindPattern(theText, Sresult)
Debug.Print 3, result, Sresult
Debug.Print "====="
End Sub
这应该是你所需要的。
在函数中,您可以注释掉任一.pattern=
语句以使用旧模式或新模式。
Subtest_Findpattern()
有三个部分,最后一个部分获取 Word 文档中的所有文本。
假设你的 word 文档包含新模式,test-sub 的输出将会是这样的:
1 Falsch
2 Wahr 1234567-3
3 Wahr 1234567-3
=====