在excel vba中找到具有完全匹配的单元格的位置

时间:2015-03-20 16:34:13

标签: excel vba excel-vba

我试图遍历range a上的sheet a,然后在range b上搜索sheet b中的每个值,然后添加到sheet b中的列1}}如果匹配。

以下是我所拥有的:

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

With循环中使用For是否存在问题?

1 个答案:

答案 0 :(得分:1)

更改以下代码:

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)中的范围期待字符串,表示范围而不是范围对象。因此出错。

编辑 - 未找到任何内容时的处理情况

为了克服没有任何资金的情况,请使用IF声明:

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