Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 用于比较单元格值的VBA宏_Excel_Vba - Fatal编程技术网

Excel 用于比较单元格值的VBA宏

Excel 用于比较单元格值的VBA宏,excel,vba,Excel,Vba,我在比较具有不同值的单元格时遇到问题,并将一个单元格中缺少的内容放入第三个单元格 例如: 我正在尝试匹配两个单元格: 单元格1(AB c d)和单元格2(CA b)都有“AB c”的共同点,我希望宏显示出来 单元格3中缺少显示的值“d” 考虑: Public Function WhatsMissing(Big As String, Little As String) As String Dim V As String V = Big For i = 1 To Len(Li

我在比较具有不同值的单元格时遇到问题,并将一个单元格中缺少的内容放入第三个单元格

例如:

我正在尝试匹配两个单元格:

单元格1(AB c d)和单元格2(CA b)都有“AB c”的共同点,我希望宏显示出来

单元格3中缺少显示的值“d”

考虑:

Public Function WhatsMissing(Big As String, Little As String) As String
    Dim V As String
    V = Big
    For i = 1 To Len(Little)
        ch = Mid(Little, i, 1)
        V = Replace(V, ch, "")
    Next i
    WhatsMissing = V
End Function
因此,如果A1包含abcdefg且B1包含def,则=缺失的内容(A1,B1)将显示:


abcg

如果您的值中肯定有空格,那么您可以使用split函数将其拆分,并将其放入数组(或字典对象)中,比较两个字典的差异

下面是一个简单的例子:

Option Explicit

Sub getDifferences()
    Dim s1() As String
    Dim s2() As String

    s1 = Split(Range("A1").Value, " ") ' a b c d
    s2 = Split(Range("B1").Value, " ") ' c a b

    Dim d1 As Object
    Dim d2 As Object

    Set d1 = CreateObject("Scripting.Dictionary")
    Set d2 = CreateObject("Scripting.Dictionary")

    ' collect the values from cell 1
    Dim i As Long
    For i = 0 To UBound(s1)
        d1.Add s1(i), i
    Next

    ' collect the values from cell 2
    For i = 0 To UBound(s2)
        d2.Add s2(i), i
    Next


    Dim missing As Object
    Set missing = CreateObject("Scripting.Dictionary")
    Dim sKey As Variant

    ' check missing items from first cell to second
    For Each sKey In d1.keys()
        If (d2.exists(sKey) = False) Then
            missing.Add sKey, 1
        End If
    Next

    ' check missing items from second cell to first
    For Each sKey In d2.keys()
        If (d1.exists(sKey) = False) Then
            missing.Add sKey, 1
        End If
    Next

    ' display the missing items between the two
    For Each sKey In missing.keys()
        Debug.Print sKey
    Next


End Sub
如果单元格1有:a b c d

第2个细胞有:CABE

这将打印出:d e


希望这有帮助

他们的字母之间总是有空格吗?为什么宏的公式会快得多?是的,他们的字母之间总是有空格