用于检测格式差异的最佳代码



我需要比较两个格式化的字符串。它们中的文本相同,只是格式不同,这意味着某些单词是粗体的。代码应该告诉我粗体子字符串的位置是否不同,例如字符串的格式不同。到目前为止,我尝试了一种字符到字符的方法,但它太慢了。

它是 MS Word 中的纯合法当前文本,每个字符串 cca 10-500 个字符。两个人独立格式化字符串。

到目前为止我的代码:

Function collectBold(r As Range) As String
Dim chpos As Integer
Dim ch As Variant
Dim str, strTemp As String
chpos = 1
Do
If r.Characters(chpos).Font.Bold Then
    Do
        Dim boold As Boolean
        strTemp = strTemp + r.Characters(chpos)
        chpos = chpos + 1
        If (chpos < r.Characters.Count) Then boold = r.Characters(chpos).Font.Bold
    Loop While (boold And chpos < r.Characters.Count)
   str = str + Trim(strTemp) + "/"
   strTemp = ""
Else: chpos = chpos + 1
End If
Loop While (chpos < r.Characters.Count)
collectBold = str
End Function

此代码收集所有粗体子字符串 (strTemp) 并将它们合并为一个字符串 (str),并用"/"分隔它们。该函数运行两个字符串进行比较,然后检查输出是否相同。

如果你只需要看看它们是否不同,这个函数就可以了:

Function areStringsDifferent(range1 As Range, range2 As Range) As Boolean
    Dim i As Integer, j As Integer
    For i = 1 To range1.Words.Count
        'check if words are different formatted
        If Not range1.Words(i).Bold = range2.Words(i).Bold Then
            areStringsDifferent = True
            Exit Function
        'words same formatted, but characters may not be
        ElseIf range1.Words(i).Bold = wdUndefined Then
            For j = 1 To range1.Words(i).Characters.Count
                If Not range1.Words(i).Characters(j).Bold = range2.Words(i).Characters(j).Bold Then
                    areStringsDifferent = True
                    Exit Function
                End If
            Next
        End If
    Next
    areStringsDifferent = False
End Function

它首先查看单词的格式是否不同...如果它们具有相同的格式但格式未定义,则会查看单词的字符。

最新更新