下面是一个使用宏来匹配来自两个不同工作表的数据的示例:
首先,打开Excel并创建两个工作表,假设一个工作表名为"Sheet1",另一个工作表名为"Sheet2"。
在"Sheet1"工作表中,输入以下数据:
A | B |
---|---|
Name | Score |
Alice | 80 |
Bob | 75 |
John | 90 |
在"Sheet2"工作表中,输入以下数据:
A | B |
---|---|
Name | Grade |
Alice | A |
Bob | B |
John | A |
在Excel中按下ALT + F11打开VBA编辑器。
在VBA编辑器中,插入一个新的模块。
在新模块中,输入以下VBA代码:
Sub MatchData()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim lastRow1 As Long
Dim lastRow2 As Long
Dim i As Long
Dim j As Long
' 设置工作表对象
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
' 获取每个工作表的最后一行
lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
lastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
' 循环遍历Sheet1中的数据
For i = 2 To lastRow1
' 循环遍历Sheet2中的数据
For j = 2 To lastRow2
' 判断名称是否匹配
If ws1.Cells(i, "A").Value = ws2.Cells(j, "A").Value Then
' 如果匹配,则在Sheet1的C列中写入对应的分数
ws1.Cells(i, "C").Value = ws2.Cells(j, "B").Value
Exit For
End If
Next j
Next i
MsgBox "数据匹配完成!"
End Sub
关闭VBA编辑器。
在Excel中按下ALT + F8打开宏对话框。
选择"MatchData"宏并点击"运行"按钮。
程序将遍历"Sheet1"工作表中的每一行数据,并在"Sheet2"工作表中查找匹配的名称。如果找到匹配的名称,则在"Sheet1"工作表的C列中写入对应的分数。
最后,弹出一个消息框,显示数据匹配完成的消息。
这是一个简单的示例,演示如何使用宏来匹配来自两个不同工作表的数据。根据实际需求,你可能需要根据需要进行修改和调整。