我试图遍历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
是否存在问题?
答案 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