Excel 比较两列并找到匹配的行
我编写了一个VBA代码,将第一列与第二列匹配,并返回第二行中不可用的第一行的条目。下面是我在脚本中使用的示例代码 现在的问题是列的匹配不正确,一些匹配的值也出现在输出中。有人能帮我找到我错的地方吗Excel 比较两列并找到匹配的行,excel,ms-office,vba,Excel,Ms Office,Vba,我编写了一个VBA代码,将第一列与第二列匹配,并返回第二行中不可用的第一行的条目。下面是我在脚本中使用的示例代码 现在的问题是列的匹配不正确,一些匹配的值也出现在输出中。有人能帮我找到我错的地方吗 Dim c As Range, d As Range Dim LastRow1 As Integer Dim LastRow2 As Integer Dim rng1 As Range, rng2 As Range, rng3 As Range shPort_Code.Activate LastRo
Dim c As Range, d As Range
Dim LastRow1 As Integer
Dim LastRow2 As Integer
Dim rng1 As Range, rng2 As Range, rng3 As Range
shPort_Code.Activate
LastRow1 = Cells(Rows.Count, "B").End(xlUp).Row
LastRow2 = Cells(Rows.Count, "J").End(xlUp).Row
For i = 4 To LastRow1
Set rng1 = shPort_Code.Range("B" & i)
For j = 2 To LastRow2
Set rng2 = shPort_Code.Range("J" & j)
'If rng1.Text='
If StrComp(rng1.Text, rng2.Text, 1) = 0 Then
'rng1.Cells("D" & i).Value.Copy Destination:=shPort_Code.Range("J2")
rng1.Value = Null
'Else
'rng1.Text.Select
End If
Next j
If Not Match Then
Range("J" & Range("J" & Rows.Count).End(xlUp).Row + 1) = rng1
End If
Next i
提前谢谢
Renu添加一些数据示例以及预期和错误的输出可能会有所帮助。我尝试了你的代码。但它给了我相同的输出。我不知道我哪里出错了。你可以在这里添加值,这样我就可以看到你试图实现的目标。
Sub compare()
Dim LastRow1 As Long, LastRow2 As Long, i As Integer, j As Integer, rowA As Integer, found As Integer, x As Integer
With ActiveSheet
LastRow1 = .Cells(.Rows.Count, "B").End(xlUp).Row *'last row from B*
LastRow2 = .Cells(.Rows.Count, "J").End(xlUp).Row *'last row from J*
End With
rowA = 1
found = 0
For i = 4 To LastRow1
For j = 2 To LastRow2
x = StrComp(Cells(i, 2).Value, Cells(j, 10).Value, 1)
If x = 0 Then *'if equal*
found = 1 *'value from column B is in column J*
End If
Next j
If found = 0 Then *'if the value is not in column J*
Cells(rowA, 1).Value = Cells(i, 2).Value *'copy the value in column A*
rowA = rowA + 1
Else
found = 0 *'set found back to 0 for the next comparison*
End If
Next i
End Sub