比较2栏中的2栏并显示匹配,但不显示不匹配

这是我的代码。 这将比较来自不同纸张(2张)的2列,然后在另一张纸张中反映出答案,但未能显示不匹配的数据。 我碰到一个错误,说运行时间'91':对象variablesr块variables未设置。

这是代码。 请帮忙。

Sub lookup() Dim TotalRows As Long Dim rng As Range Dim i As Long 'Copy lookup values from sheet1 to sheet3 Sheets("Sheet1").Select TotalRows = ActiveSheet.UsedRange.Rows.Count Range("A1:A" & TotalRows).Copy Destination:=Sheets("Sheet3").Range("A1") 'Go to the destination sheet Sheets("Sheet3").Select For i = 1 To TotalRows 'Search for the value on sheet2 Set rng = Sheets("Sheet2").UsedRange.Find(Cells(i, 1).Value) 'If it is found put its value on the destination sheet If Not rng Is Nothing Then Cells(i, 2).Value = rng.Value Else Cells(i, 4).Value = rng.Value <------------stops here End If Next End Sub 

改变这个:

 Cells(i, 4).Value = rng.Value 

对此:

 Cells(i, 4).Value = "Not found" 

如果找不到匹配项,您正尝试将Nothing分配给单元格:

 If Not rng Is Nothing Then Cells(i, 2).Value = rng.Value 'rng has a value Else Cells(i, 4).Value = rng.Value 'rng has NO value, ie is Nothing End If 

这是不可能的,这就是为什么你得到错误。