在excel vba中find与精确匹配的单元格的位置

我试图循环遍历工作sheet a range b上的range b sheet b ,然后search工作sheet b上的range b每个值,然后添加到工作sheet b的列(如果匹配的话)。

这是我得到的:

 Function add_column_binary(sheet_name_from As String, col_from As Integer, sheet_to As String, col_to As Integer) ' set range - the range to be looped through to find key for serachign the second range Dim first_range As Range Set first_range = set_range(sheet_name_from, col_from) ' set ragen - the range in teh second sheet to be repeatedly searched Dim second_range As Range Set second_range = set_range(sheet_to, col_to) ' find last column Dim last_col As Integer last_col = Worksheets(sheet_to).Cells(1, Columns.Count).End(xlToLeft).column ' label last column Worksheets(sheet_to).Cells(1, last_col + 1).Value = "Invited = 1" Dim rows1 As Long rows1 = first_range.Cells(rows.Count, col_from).End(xlUp).Row + 1 Dim n As Long Dim constructed_id As String Dim find_result As Range For n = 2 To rows1 constructed_id = "ObjectID(" & first_range.Cells(n, 1) & ")" ' format object id ' **** I keep getting "run-time error '1004':" **** ' **** "Application-defined or object-defined error" **** With Worksheets(sheet_to).Range(second_range) Set find_result = .Find(constructed_id, LookIn:=xlValues, lookat:=xlWhole) End With Next n Stop End Function Sub test_stuff() Dim x As Range Set x = add_column_binary("invitesOutput.csv", 3, "usersFullOutput.csv", 1) End Sub 

For循环中使用With有问题吗?

更改下面的代码:

 With Worksheets(sheet_to).Range(second_range) Set find_result = .Find(constructed_id, LookIn:=xlValues, lookat:=xlWhole) End With 

对此:

 Set find_result = second_range.Find(constructed_id, LookIn:=xlValues, lookat:=xlWhole) 

原因: second_range已被定义为一个范围,您可以将其用于Find()方法。
Worksheets(sheet_to).Range(second_range)范围 Worksheets(sheet_to).Range(second_range)期待一个String,表示一个Range而不是Range对象 。 所以一个错误。

编辑 – 处理情况,当没有发现

为了克服这种情况,在没有任何东西正在使用IF语句时:

 If Not find_result Is Nothing then 'Not Is Nothing, in other words is something 'Your code End if