2017-07-17 53 views
-1

我有兩張「紙張A」和「紙張B」,「紙張A」包含一些數據,「紙張B」包含所有數據。所以如果我「工作表A」沒有任何數據,而不是在工作表B中我想顯示消息。微軟VBA比較兩列並顯示錯誤信息

VBA代碼

Private Sub CommandButton1_Click() 
Dim myRng As Range 
    Dim lastCell As Long 

    'Get the last row 
    Dim lastRow As Integer 
    lastRow = ActiveSheet.UsedRange.Rows.Count 

    'Debug.Print "Last Row is " & lastRow 

    Dim c As Range 
    Dim d As Range 

    Application.ScreenUpdating = False 

    For Each c In Worksheets("Sheet1").Range("A2:A" & lastRow).Cells 
     For Each d In Worksheets("Sheet2").Range("A2:A" & lastRow).Cells 
      c.Interior.Color = vbRed 
      If (InStr(1, d, c, 1) > 0) Then 
       c.Interior.Color = vbWhite 
       Exit For 
      End If 
     Next 
    Next 

    For Each c In Worksheets("Sheet2").Range("A2:A" & lastRow).Cells 
     For Each d In Worksheets("Sheet1").Range("A2:A" & lastRow).Cells 
      c.Interior.Color = vbRed 
      If (InStr(1, d, c, 1) > 0) Then 
       c.Interior.Color = vbWhite 
       Exit For 
      End If 
     Next 
    Next 

Application.ScreenUpdating = True 
End Sub 
+2

什麼問題?不要讓我們猜... –

+1

嘗試vlookup,可能會更容易,然後使用vba。 – Jonnyboi

+0

或'countif'或數組公式。你沒有說過這是內容還是內容的一部分。 'instr'暗示它可能是123ABC456中的ABC,但不確定。指示什麼,何時何地以及任何其他背景可以提供幫助。 –

回答

0

,如果您有基於列的數據你可以試試這個公式。這將出現在您的數據旁邊的工作表A上(A1是您的數據,B1是公式),並在工作表B(匹配範圍=工作表B,列x)中查找工作表A的A列。

=IF(ISNUMBER(MATCH(LookupValue,MatchRange,0)),"Yes","No")