如果找到匹配第一张第4列的复制值到第二张,则比较3张两张纸

时间:2017-11-27 10:43:41

标签: excel-vba vba excel

我正在尝试比较工作簿中两个工作表中的3列,如果所有3列匹配,则将第一个工作表(G列)的值复制到第二个工作表的P列。 我试图使用下面的代码,但它似乎不起作用。(返回空白)

Sub CopyCells()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim j As Long, i As Long, lastrow1 As Long, lastrow2 As Long
    Set sh1 = Worksheets("EOD")
    Set sh2 = Worksheets("Consolidated")

    lastrow1 = sh1.Cells(Rows.Count, "A").End(xlUp).Row
    lastrow2 = sh2.Cells(Rows.Count, "A").End(xlUp).Row

    For i = 2 To lastrow1
        For j = 2 To lastrow2
            If sh1.Cells(i, "A").Value = sh2.Cells(j, "B").Value And _
                sh1.Cells(i, "B").Value = sh2.Cells(j, "C").Value And _
                sh1.Cells(i, "C").Value = sh2.Cells(j, "D").Value Then
                sh1.Cells(i, "G").Value = sh2.Cells(j, "P").Value
            End If
        Next j
    Next i
End Sub

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我已经测试了以下代码,它可以按照您的需要进行测试:

Sub CopyCells()
LastRow1 = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
LastRow2 = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row

For i = 2 To LastRow1
    For j = 2 To LastRow2
        If Sheet1.Cells(i, "A").Value = Sheet2.Cells(j, "B").Value Then
            If Sheet1.Cells(i, "B").Value = Sheet2.Cells(j, "C").Value Then
                If Sheet1.Cells(i, "C").Value = Sheet2.Cells(j, "D").Value Then
                    Sheet2.Cells(j, "P").Value = Sheet1.Cells(i, "G").Value
                End If
            End If
        End If
    Next j
Next i
End Sub