2016-06-28 28 views

回答

0

問題中沒有太多的信息。但是按照以下假設,下面的代碼會給出結果,如圖所示。

假設:

正如在相應的名字問題比賽所提到的,我假設你想匹配的數據行的明智即比賽ROW1-ROW1,ROW2,ROW2,等等。
2.兩個要比較的文件分別爲file1file2,其數據分別爲Sheet3Sheet2。 (根據需要更改文件名稱和表名稱)
3.最終的結果是在紅色顏色凸顯綠色和非匹配的名稱匹配的名稱。 (因爲一切都沒有問題有關所需的輸出,我也顯示「匹配」和「不匹配」在file2作爲另一種選擇指定)

Sub Compare() 
    Dim ws1 As Worksheet, ws2 As Worksheet 
    Dim lastRow As Long, matchCount As Long 

    'two sheets to be used of different files 
    Set ws1 = Workbooks("file1").Sheets("Sheet3") 
    Set ws2 = Workbooks("file2").Sheets("Sheet2") 

    matchCount = 0 

    'get last row with data from file1   
    lastRow = ws1.Cells(Rows.Count, "A").End(xlUp).Row 

    'loop through all the names in column A 
    'starting with 2 to exclude header 
    For i = 2 To lastRow 
     If ws1.Range("A" & i) = ws2.Range("A" & i) Then 
      'if names match change cell color to green in file2 
      'also write match in column B 
      ws2.Range("A" & i).Interior.ColorIndex = 43 
      ws2.Range("A" & i).Offset(0, 1).Value = "Match" 
      matchCount = matchCount + 1 
     Else 
      'if names does not match change cell color to red in file2 
      'also write no match in column B 
      ws2.Range("A" & i).Interior.ColorIndex = 3 
      ws2.Range("A" & i).Offset(0, 1).Value = "No Match" 
     End If 
    Next 

    MsgBox "Out of " & lastRow - 1 & " there were " & matchCount & " cells matching." 
End Sub 

注:這兩個文件應該是在同一個實例中打開的Excel的代碼工作。

enter image description here

相關問題