簡體   English   中英

使用VBA比較不同工作表中的單元格並在單元格不匹配時在一張工作表上插入新行

[英]Using VBA To Compare Cells From Different Sheets And Insert New Row On One Sheet When Cells Don't Match

我有兩個工作表,其中我需要將工作表Blah中的實體ID與工作表Blah1中的實體ID進行比較。 實體ID存儲在兩張紙的A列中。 如果Blah中存在實體ID,但Blah 1中不存在,則需要在Blah 1表上插入空白行,該行缺少實體ID。 我需要比較的行范圍將逐月變化。 我知道Blah 2上的第5到92行與第2到89行匹配,但是它從第11行開始插入,並繼續插入行,直到我碰到逃脫。 我知道如果實體ID為空,如果告訴代碼轉到下一個我,我可能還需要另一個,但是我不確定該怎么做。

因此,總而言之,我需要比較實體ID,並為缺少的任何實體ID插入新行。 任何幫助將不勝感激。

 Sub InsertNewRow()
 Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long

 lastrow1 = Sheets("Blah").Range("A" & Rows.Count).End(xlUp).Row
 lastrow2 = Sheets("Blah1").Range("A" & Rows.Count).End(xlUp).Row

     For j = 2 To lastrow2
      For i = 5 To lastrow1
        If Sheets("Blah").Cells(j, 1) <> Sheets("Blah1").Cells(i, 1) Then
            Sheets("Blah1").Cells(i, 1).EntireRow.Insert
 End If
     Next i
 Next j
 End Sub

實際上,我可以在Excel先生身上找到答案。 我認為是雙重Fors困擾了我。 一旦找到答案,我就能弄清楚如何將所需的值從表Blah添加到表Blah1。 在基於斯科特所說的內容進行搜索時,我找不到真正需要的東西。 我敢肯定,有一種更簡單的方法可以做到這一點,隨着我獲得更多的經驗,也許我會弄清楚的。

    Sub InsertRows()
     Dim lastrow As Long, i As Long, j As Long

     lastrow = Sheets("Blah").Range("A" & Rows.Count).End(xlUp).Row
    j = 14

    For i = 2 To lastrow
    If Sheets("Blah1").Cells(j, 1).Value <> Sheets("Blah").Cells(i, 1).Value Then
     Sheets("Blah1").Rows(j).Insert Shift:=xlDown
    Sheets("Blah1").Cells(j, 2).Value = Sheets("Blah").Cells(i, 10).Value
    Sheets("Blah1").Cells(j, 3).Value = Sheets("Blah").Cells(i, 11).Value
    Sheets("Blah1").Cells(j, 5).Value = "2017"
    Sheets("Blah1").Cells(j, 6).Value = Sheets("Blah").Cells(i, 2).Value
    Sheets("Blah1").Cells(j, 7).Value = Sheets("Blah").Cells(i, 3).Value
    Sheets("Blah1").Cells(j, 8).Value = Sheets("Blah").Cells(i, 4).Value
     Sheets("Blah1").Cells(j, 9).Value = Sheets("Blah").Cells(i, 5).Value

    End If
     j = j + 1
    Next i
    End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM