我编写了一个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
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
提前致谢。
雷努
答案 0 :(得分:0)
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