使用vba在excle中写这个代码,查找sheet1中A列姓名是否在于sheet2中A列姓名,如果存在将sheet2中的整行复制到sheet3中。
时间: 2023-09-24 11:06:34
浏览: 87
### 回答1:
下面是在 VBA 中写出查找并复制的[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083):
Sub CopyRows()
Dim i As Long, l[ast](https://geek.csdn.net/educolumn/1d2c256574d93ae646d4473629b198e6?spm=1055.2569.3001.10083)Row1 As Long, lastRow2 As Long
Dim name1 As [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083), name2 As [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)
' 获取 sheet1 和 sheet2 中的最后一行
lastRow1 = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
lastRow2 = Sheet2.Range("A" & Rows.Count).End(xlUp).Row
' 遍历 sheet1 中的每一行
For i = 1 To lastRow1
name1 = Sheet1.Range("A" & i).Value
' 在 sheet2 中查找该姓名是否存在
Dim j As Long
For j = 1 To lastRow2
name2 = Sheet2.Range("A" & j).Value
If name1 = name2 Then
' 如果存在,复制该行到 sheet3 中
Sheet2.Range("A" & j & ":Z" & j).Copy Destin[ati](https://geek.csdn.net/educolumn/150d7073277950db5f09620704e791cf?spm=1055.2569.3001.10083)on:=Sheet3.Range("A" & Rows.Count).End(xlUp).Offset(1)
Exit For
End If
Next j
Next i
End Sub
```