写一个vba代码,实现以下需求,1.将表1表2的A列匹配,如果匹配一致则退出循环,2.如果匹配不一致,则将表1与表2的B列进行匹配,3.如果A列匹配一致不执行B列匹配,如果A列匹配不一致,则执行B列匹配,4.A列匹配一致在C列返回Y,如果B列匹配一致,在D列返回Y
时间: 2024-02-02 16:05:33 浏览: 69
根据您的需求,我编写了以下代码:
```
Sub MatchColumns()
Dim ws1 As, ws2 As Worksheet
Dim lastRow1 Long, lastRow2 As Long
i As Long, j As Long
Dim matchFound As Boolean
Set ws1 = ThisWorkbook.Worksheets("表1") '将“表1”替换成表1所在的工作表名称
Set ws2 = ThisWorkbook.Worksheets("表2") '将“表2”替换成表2所在的工作表名称
lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row '获取表1最后一行的行号
lastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row '获取表2最后一行的行号
For i = 2 To lastRow1 '从表1的第二行开始循环
matchFound = False '重置匹配标志为False
For j = 2 To lastRow2 '从表2的第二行开始循环
If ws1.Cells(i, "A").Value = ws2.Cells(j, "A").Value Then '如果表1的A列和表2的A列匹配一致
ws1.Cells(i, "C").Value = "Y" '在表1的C列返回Y
matchFound = True '将匹配标志设为True
Exit For '退出表2的循环
End If
Next j
If Not matchFound Then '如果A列匹配不一致,则执行B列匹配
For j = 2 To lastRow2 '从表2的第二行开始循环
If ws1.Cells(i, "B").Value = ws2.Cells(j, "B").Value Then '如果表1的B列和表2的B列匹配一致
ws1.Cells(i, "D").Value = "Y" '在表1的D列返回Y
Exit For '退出表2的循环
End If
Next j
End If
Next i
End Sub
```
您可以将代码复制到VBA编辑器中,然后运行它。请确保将“表1”和“表2”替换为实际表格的工作表名称。此代码将在表1的C列返回Y,如果A列匹配一致,在表1的D列返回Y,如果B列匹配一致。
阅读全文
相关推荐
















