我正在尝试将sheet2中的列A与sheet1中的columnA进行比较,当匹配时,将行从sheet1复制到sheet3 . 这是我的代码,但它不起作用 .
Sub compareAndCopy()
Dim lastRowE As Integer
Dim lastRowM As Integer
Dim foundTrue As Boolean
' stop screen from updating to speed things up
Application.ScreenUpdating = False
lastRowE = Sheets("Sheet2").Cells(Sheets("Sheet2").Rows.Count, "A").End(xlUp).Row
lastRowF = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "A").End(xlUp).Row
lastRowM = Sheets("Sheet3").Cells(Sheets("Sheet3").Rows.Count, "B").End(xlUp).Row
For i = 1 To lastRowE
foundTrue = False
For j = 1 To lastRowF
If Sheets("Sheet2").Cells(i, 1).Value = Sheets("Sheet1").Cells(j, 1).Value Then
'MsgBox ("didnt find string: " & Sheets("Sheet2").Cells(i, 2).value)
Sheets("Sheet2").Rows(i).Copy Destination:= _
Sheets("Sheet3").Rows(lastRowM + 1)
Exit For
End If
Next j
If Not foundTrue Then
lastRowM = lastRowM + 1
foundTrue = True
End If
Next i
' stop screen from updating to speed things up
Application.ScreenUpdating = True
End Sub
2 回答
正如Scott Craner指出的那样,基于
foundTrue
更新lastRowM
无法正常工作 . 只要每次向Sheet3添加新行时更新lastRowM
,都不需要foundTrue
. 我已将其保存在代码中,以防您在未找到值时显示消息.2923494_遵循你的措辞:
你可以试试这个