检测文本相同但文本格式不同的单元格之间的差异

时间:2018-07-12 21:21:43

标签: excel vba

我想检测两个单元格之间有关文本的内容是否有所不同。

例如,单元格A1和B1具有相同的文本,但文本格式不同:

  

单元格A1:这是我的单元格。

     

单元格B1:这是我的 单元格。

以下代码没有区别:

'if the text in the cells is different in any way, report a difference
If (ActiveSheet.Cells(1, "A") <> ActiveSheet.Cells(1, "B")) Then
    ActiveSheet.Cells(1, "C").Value = DIFFERENT
End If

2 个答案:

答案 0 :(得分:3)

例如:

Sub Tester()
    Debug.Print SameText(Range("B4"), Range("C4"))
End Sub

'call from VBA or as UDF
Function SameText(rng1 As Range, rng2 As Range) As Boolean
    Dim rv As Boolean, c1, c2, x As Long, arr, v

    If rng1.Value = rng2.Value Then
        rv = True
        arr = Array("Underline", "Fontstyle", "Color") '<< for example
        For x = 1 To Len(rng1.Value)
            Set c1 = rng1.Characters(x, 1).Font
            Set c2 = rng2.Characters(x, 1).Font
            For Each v In arr
                If CallByName(c1, v, VbGet) <> CallByName(c2, v, VbGet) Then
                    Debug.Print "Mismatch on " & v & " at position " & x, _
                                 rng1.Address, rng2.Address
                    rv = False
                    Exit Function
                End If
            Next
        Next x
    Else
        rv = False
    End If

    SameText = rv
End Function

答案 1 :(得分:1)

我不确定比较单元格的.Value(11)XML代码是否可以捕获您要查找的所有差异,但是可以捕获示例字符串格式中的差异。

With ActiveSheet
    Debug.Print .Cells(1, "A").Value(11)
    Debug.Print .Cells(1, "B").Value(11)
    If .Cells(1, "A").Value(11) <> .Cells(1, "B").Value(11) Then
      .Cells(1, "C").Value = "DIFFERENT"
    End If
End With

对于未格式化的单元格,此元素非常简单。

...
<Cell><Data ss:Type="String">abcdef</Data></Cell>
...

使用粗体和删除线字符格式化的格式不是这样。

...
<Cell><ss:Data ss:Type="String" xmlns="http://www.w3.org/TR/REC-html40"><Font
   html:Color="#000000">ab</Font><B><S><Font html:Size="8.8000000000000007"
     html:Color="#000000">cde</Font></S></B><Font html:Color="#000000">f</Font></ss:Data></Cell>
...

仅比较该元素,

Dim val11A As String, val11B As String

With ActiveSheet
    val11A = Split(Split(.Cells(1, "A").Value(11), "<Cell>")(1), "</Cell>")(0)
    val11B = Split(Split(.Cells(1, "B").Value(11), "<Cell>")(1), "</Cell>")(0)
    If val11A <> val11B Then
      .Cells(1, "C").Value = "DIFFERENT"
    End If
End With