2017-04-03 90 views
-1

我是VBA的新手,我正在尋找一個簡單的VBA代碼來比較2行併合並/複製數據,如果在工作表中有不同的數據。VBA比較2列和合並/警察

我想與可倫甲在片1

比較科拉姆甲在片材2如果科拉姆A中的ID是在片1中,在科拉姆B和C與來自數據更新數據等於科拉姆甲片1

如果從片材1中的ID不存在於片材2,添加科拉姆A,B,C到片2

以上是否有意義或?

BR 而且。

回答

0

我沒有通過這個測試所有場景。像這樣做的東西適用於你想要做的事情嗎?這確實假設在Sheet2中存在0或1個ID。此外,假定第1行有列標題,而不是實際數據。

Public Sub CheckSheet2() 


    Dim source_sheet As Worksheet 
    Set source_sheet = ActiveWorkbook.Worksheets("Sheet1") 
    Dim source_last_row As Long 
    source_last_row = source_sheet.Range("A" & source_sheet.Rows.Count).End(xlUp).Row 

    Dim target_sheet As Worksheet 
    Set target_sheet = ActiveWorkbook.Worksheets("Sheet2") 
    Dim target_last_row As Long 
    target_last_row = target_sheet.Range("A" & target_sheet.Rows.Count).End(xlUp).Row 

    Dim source_row As Long 
    For source_row = 2 To source_last_row 

     Dim source_str As String 
     source_str = source_sheet.Range("A" & source_row).Value 

     Dim found_value As Range 
     Set found_value = target_sheet.Range("A2:A" & target_last_row).Find(source_str) 

     If Not found_value Is Nothing Then 
      target_sheet.Range(found_value.Address).Offset(0, 1).Value = source_sheet.Range("B" & source_row).Value 
      target_sheet.Range(found_value.Address).Offset(0, 2).Value = source_sheet.Range("C" & source_row).Value 
     Else 
      target_last_row = target_last_row + 1 
      target_sheet.Range("A" & target_last_row).Value = source_sheet.Range("A" & source_row).Value 
      target_sheet.Range("B" & target_last_row).Value = source_sheet.Range("B" & source_row).Value 
      target_sheet.Range("C" & target_last_row).Value = source_sheet.Range("C" & source_row).Value 
     End If 

    Next source_row 

End Sub 

您顯然需要將Sheet1和Sheet2的值更改爲工作表名稱。

在我運行程序之前,我在Sheet1中看起來像這樣。

enter image description here

而這是在Sheet2中運行該程序之前。通知ID 127和128丟失。

enter image description here

這是Sheet2的樣子運行程序後。

enter image description here

+0

很多謝謝它的作品像一場夢。 :-) – And