2015-09-24 78 views
0

我期待在Excel 2013中的工作簿中做兩張比較。由於記錄數VLOOKUP和其他公式一直慢,所以我想我會嘗試VB看看是否這樣是一個更快的解決方案。比較兩張使用ID列

我想要做的是比較每個記錄的ID和突出顯示和紅色不匹配。由於列名和位置不同,我還想通過指定列名進行比較來對每條記錄進行單元格比較。最後,我想將每列的不匹配總和轉換爲第三個表格。

例如:

Sheet 1: 
ID Col1 Col2 Col3 Col4 
1 1  1  1  1 
2 2  2  2  1 
3 3  3  3  3 
4 4  4  4  4 

Sheet 2: 
DBID Col1 Col2 Field Col3 
1  1  1  1  1 
2  2  2  2  2 
4  4  4  4  4 
3  3  3  3  3 

因此,在上面的例子中我只想COL4與字段列和只能看到ID字段列2突出顯示爲與ID記錄3忽略,因爲錯誤和4相比他們匹配並且只是在文件中的不同位置。

我通常會對ID進行排序,而不是挑出某個特定的ID,但意識到可能有缺失的記錄,這意味着數據會錯位。

目前我發現這個代碼將突出顯示紅色的不匹配,但匹配逐個單元格,而不考慮列和記錄可能不在同一順序。

Sub RunCompare() 'Call the compareSheets routine Call compareSheets("Sheet1", "Sheet2") End Sub 

    Sub compareSheets(shtBefore As String, shtAfter As String) Dim mycell As Range Dim mydiffs As Integer 'If current cell is not a date then proceed (else skip and go to next), then 'if not same as corresponding cell in sheet After, 'mark as yellow and repeat until entire range is used For Each mycell In ActiveWorkbook.Worksheets(shtAfter).UsedRange If Not IsDate(mycell) Then 
    If Not mycell.Value = ActiveWorkbook.Worksheets(shtBefore).Cells(mycell.Row, mycell.Column).Value Then 

     mycell.Interior.Color = vbRed 
     mydiffs = mydiffs + 1 

    End If End If Next 'Display a message box stating the number of differences found MsgBox mydiffs & " differences found", vbInformation ActiveWorkbook.Sheets(shtAfter).Select End Sub 
+0

請參見[我應該使用標籤標題?](http://meta.stackexchange.com/help/tagging)。 – pnuts

回答

0

我假設ID是唯一的。

基本上有兩種解決方案,有和沒有宏。

隨着宏邏輯可以如下:

循環通過第一(唯一)柱獲取第一片材的第一(唯一)柱,並找到在第二片材的匹配行 該行中的細胞之間比較與第一行第一頁 對所有行重複相同的步驟

也做一個檢查,看看兩個工作表是否有相同數量的行和列;並沒有行重複。

非宏解決方案:

使用VLOOKUP函數來查找匹配的值的行和在一個新的片做一個相等的比較公式作爲

= IF(Sheet 1中 1 = VLOOKUP(! Sheet1!A1,Sheet2!A:Z,,FALSE),「Same」,「Different」)

請注意,您需要增加行號和列名,第三(答案)表。

一旦你的價值觀,你可以使用條件格式來突出不同的,以紅