vba - 检测格式差异的最佳代码?

标签 vba ms-word

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

它是 MS Word 中的普通合法当前文本,每个字符串大约 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

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

关于vba - 检测格式差异的最佳代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21042991/

相关文章:

vba - 打开文件中的宏 如果你在开会,点击 "OK",如果没有,在excel中再次提及

Excel VBA获取和使用表名

delphi - 在 Delphi 中处理 Word 的退出事件

vba - 如何检测当前打开的 swf 文件名

vba - 如何在更改下拉菜单时在 VBA 中从 Excel 运行 SQL 查询

c# - 使用 C#/Java/Visual Basic 填充 Word 2007 模板

vba - 查找 Excel 电子表格和 VBA 数组之间的匹配项

vb.net - 当保护 View 打开时如何使用Word对象?

excel - 通过按宏按钮将行从一张纸复制并插入到另一张纸上

vba - 如何循环遍历具有拆分单元格的单词表格中的所有单元格