2013-11-04 90 views
0

我在比較具有不同值的單元格時遇到問題,並給出了在一個單元格中丟失的單元格到第三個單元格中的情況。用於比較單元格值的VBA宏

例子:

我想匹配的兩個單元:

細胞1(ABCD)&細胞2(駕駛室)都具有共同的 「ABC」,我想宏觀展現

在細胞中顯示

缺失值 「d」。3.

+1

他們會在字母之間總是有空格嗎? –

+0

爲什麼宏一個公式會更快? – user2140261

+0

是的,他們之間會一直有空間 – user2954015

回答

0

考慮:

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包含高清然後= WhatsMissing(A1,B1)將顯示:

ABCG

0

如果你的價值觀會在他們的空間是肯定的,那麼你可以用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有:ABCD

和細胞2有:CABE

這將打印出:德

希望這有助於