在内层循环中,写一个VBA代码,实现以下需求,将表1的I列与表2的H列匹配,如果匹配一致,将表2的I值返回给表1的E列,如果匹配不一致,则执行表1的H列与表2的E列匹配,匹配一致则将表2的F值返回给表1E列,如果前两次匹配都不一致,则退出这个循环
时间: 2024-02-24 08:53:19 浏览: 59
vba自动对齐工具
以下是实现你所需求的VBA代码:
```VBA
Sub matchColumns()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastRow1 As Long, lastRow2 As Long
Dim i As Long, j As Long
Set ws1 = ThisWorkbook.Worksheets("表1")
Set ws2 = ThisWorkbook.Worksheets("表2")
lastRow1 = ws1.Cells(Rows.Count, "I").End(xlUp).Row
lastRow2 = ws2.Cells(Rows.Count, "H").End(xlUp).Row
For i = 2 To lastRow1
For j = 2 To lastRow2
If ws1.Cells(i, "I").Value = ws2.Cells(j, "H").Value Then
ws1.Cells(i, "E").Value = ws2.Cells(j, "I").Value
Exit For
ElseIf ws1.Cells(i, "H").Value = ws2.Cells(j, "E").Value Then
ws1.Cells(i, "E").Value = ws2.Cells(j, "F").Value
Exit For
ElseIf j = lastRow2 Then
Exit For
End If
Next j
Next i
End Sub
```
代码中首先定义了两个Worksheet对象ws1和ws2,分别对应表1和表2。然后通过`End(xlUp)`方法找到表1和表2的最后一行,分别保存在lastRow1和lastRow2变量中。接着通过两个嵌套的For循环遍历表1和表2的每一行数据,进行匹配。如果表1的I列和表2的H列匹配成功,则将表2的I列的值返回给表1的E列,并退出循环。如果匹配不成功,则继续判断表1的H列和表2的E列是否匹配,如果匹配成功,则将表2的F列的值返回给表1的E列,并退出循环。如果前两次匹配都不成功,则直接退出内层循环。最后,整个匹配过程结束。
阅读全文