在不同的工作簿中检查两个范围(运行时错误424)

我正在尝试检查workbook1-sheet1-A中的值是否在workbook2-sheet2-E中匹配。 如果有匹配, workbook1-sheet1-Y收到一个'x'

这是我到目前为止的代码,并给我Run time error 424 - Object required在if循环Run time error 424 - Object required错误。

 Sub Check() ' Application.ScreenUpdating = False endRow = Range("A" & Rows.Count).End(xlUp).Row wkbSLA = ("F:\Workbook2") For i = 2 To endRow If Cells(i, 1).Value = wkbSLA.Sheets("Sheet2").Range("E2:E575").Value Then Range("Y" & i) = "x" End If Next i ' End Sub 

为了确保你的代码正在做你所期待的一切,确保你用variables限定你的对象。

另外,您不能在多单元格范围内使用.Value属性。 这可能是你的错误发生的地方。 处理这个问题的更好方法是使用.Find方法。

如果你写这样的代码,它应该为你工作…虽然你可能需要调整一下,以满足您的需求。

 Option Explicit Sub Check() Application.ScreenUpdating = False Dim wkb1 as Workbook, wkb2 as workbook Set wkb1 = Workbooks("workbook1") Set wkb2 = Workbooks("F:\Workbook2") ' -> do you need Workbooks.Open("F:\Workbook2") here? ' Seems you may if the workbook you want to access is closed Dim wks1 as Worksheet, wks2 as Worksheet Set wks1 = wkb1.Sheets(1) 'may need to change this reference for your needs Set wks2 = wkb2.Sheets("Sheet2") With wks1 Dim endRow as Long endRow = .Range("A" & Rows.Count).End(xlUp).Row Dim i as Long For i = 2 To endRow Dim rng as Range Set rng = wks2.Range("E2:E575").Find .Cells(i,1).Value lookat:=xlWhole If Not rng Is Nothing Then .Range("Y" & i) = "x" Next i End With End Sub