只比较两个Word文档中的数字



是否有一个Word VBA代码可以比较两个Word文档中的数字,而不比较所有非数字文本?第一个文档始终是英语,第二个文档是其翻译(阿拉伯语、西班牙语等)。

比较的目的是确保英语和目标语言中的所有数字(数字)匹配。

正常"比较"工具比较一切(数字和文本),结果比较文档将是一个混乱)。

我在两个文档中突出显示了所有数字(使用"([0-9])"作为通配符),使用VBA代码将所有高亮提取到两个新的Word文档中,然后比较两个结果文件,但是比较没有意义。这就是为什么我希望只能对数字进行比较(保留非数字文本完整)。

下面的代码可以为您的VBA代码提供一个起点。

Sub Main()
Dim Match As Object
Dim Matches As Object
Dim match_1 As String: match_1 = ""
Dim match_2 As String: match_2 = ""
' the documents you are comparing
Dim page_1 As Document: Set page_1 = Word.Documents(1)
Dim page_2 As Document: Set page_2 = Word.Documents(2)
Dim Expression As Object: Set Expression = CreateObject("vbscript.regexp")
' expression to match positive, negative and unsigned numbers with or without a decimal place
Expression.Pattern = "[+ -]?[0-9]+([.][0-9]+)?"
Expression.Global = True
' populate match_1 with the numbers matched in the page_1
Set Matches = Expression.Execute(page_1.Content.Text)
For Each Match In Matches
If match_1 = "" Then
match_1 = Trim$(Match.Value)
Else
match_1 = match_1 & ", " & Trim$(Match.Value)
End If
Next Match
' the same for page 2
Set Matches = Expression.Execute(page_2.Content.Text)
For Each Match In Matches
If match_2 = "" Then
match_2 = Trim$(Match.Value)
Else
match_2 = match_2 & ", " & Trim$(Match.Value)
End If
Next Match
' simple compare
If match_1 = match_2 Then
Debug.Print "Match"
Else
Debug.Print "Mismatch"
End If
End Sub

最新更新