我想在VBA代码中使用VLookup来查找来自不同工作簿的值(Excel 2010 VBA)。我在下面代码的最后一行收到了上述错误:
Sub GetFundValues(Source As String, Target As String, wb As Workbook)
Dim nIdx As Integer
Dim SourceSheet As Worksheet
Dim SourceFile As Workbook
Dim s2 As String
Dim s3 As String
Dim rng As Range
s2 = wb.Sheets(Target).Range("C2").Value
Set SourceFile = Application.Workbooks.Open("D:\Mydocs\Finance\inv.xls")
Set SourceSheet = SourceFile.Worksheets(Source)
s3 = SourceSheet.Range("A3").Value
Set rng = SourceSheet.Range("A3:A30")
nIdx = 3
With wb.Sheets(Target)
While wb.Sheets(Target).Range("H" & nIdx).Value <> ""
s2 = wb.Sheets(Target).Range("H" & nIdx).Value
wb.Sheets(Target).Range("B" & nIdx).Value = Application.WorksheetFunction.VLookup(s2, rng, 3, False)
正确设置s2,s3和rng变量的值(它们用于调试目的),Vlookup(第3列)中的value列包含有效值。
我无法想象VLookup中的其他问题可能会导致这种情况。任何想法??
答案 0 :(得分:2)
刚发现这个:
Set rng = SourceSheet.Range("A3:A30")
您正在查看的范围仅为1列宽。当您尝试从第3列返回数据时,您的范围至少需要3列宽:
Set rng = SourceSheet.Range("A3:C30")