写Vba代码,sheet1中有大量的数据,sheet2只有a,b两列少量数据,根据sheet1中同时满足a列编号和b列资料名称搜索到的c列数据填写到sheet2中的c列
时间: 2023-05-11 14:07:41 浏览: 107
可以使用VBA的For Each循环来遍历Sheet1中的数据,然后使用If语句判断是否满足条件,如果满足则将对应的C列数据填写到Sheet2中的C列。具体代码如下:
Sub SearchAndFill()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim i As Long, j As Long, lastRow1 As Long, lastRow2 As Long
Dim a As String, b As String, c As String
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Set ws2 = ThisWorkbook.Worksheets("Sheet2")
lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
lastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow2
a = ws2.Cells(i, "A").Value
b = ws2.Cells(i, "B").Value
For j = 2 To lastRow1
If ws1.Cells(j, "A").Value = a And ws1.Cells(j, "B").Value = b Then
c = ws1.Cells(j, "C").Value
ws2.Cells(i, "C").Value = c
Exit For
End If
Next j
Next i
End Sub
这段代码会遍历Sheet2中的数据,然后在Sheet1中查找满足条件的数据,并将对应的C列数据填写到Sheet2中的C列。注意,这段代码假设Sheet1中的数据是按照A列编号和B列资料名称排序的,如果不是,则需要先对数据进行排序。
阅读全文