VBA变量工作簿参考运行时 - 错误9

时间:2017-12-04 13:18:47

标签: excel vba excel-vba vlookup

我正在尝试用两个单独的工作簿来做VlookUp。主要工作簿在开头就打开了支持工作簿,如下所示:

Public Sub GetFile()

Dim MySourceSheet As Variant, wb As Workbook

'Opens window to choose file from
MySourceSheet = Application.GetOpenFilename(FileFilter:= _
    "Excel Files (*.XLS; *.XLSX), *.XLS; *.XLSX", Title:="Select file to 
    retrieve data from.")
If MySourceSheet = False Then Exit Sub                       
Set wb = Workbooks.Open(MySourceSheet)                       

End Sub

在整个模块中,我引用了几次文档,然后出现了这部分错误。

  
 Private Sub VlookupToBeReviewed()

Dim LastColumn As Long

Workbooks("09_PR Status Custodians.xlsm").Activate                                           'change name
'inserts new column
With Sheets("Prio_Custodians")
    LastColumn = Cells(2, .Columns.Count).End(xlToLeft).Column                       'change row! 'defines last column
    For i = LastColumn To LastColumn Step -2                                         'moves two columns to the left
        .Columns(i).Insert
        .Columns(i).ColumnWidth = 10
    Next
End With

'puts in the date
Cells(3, LastColumn).Value = Date

'sets up the variables for the vlookup
Dim rw As Long, col As Range
Dim twb As Workbook

'sets up the workbooks
Set twb = ThisWorkbook
Set col = Workbooks(MySourceSheet).Sheets("Documents to be reviewed").Range("A:B")

'vlookup function
With twb.Sheets("Sheet1")
    For rw = 3 To .Cells(Rows.Count, 1).End(xlUp).Row
        .Cells(rw, LastColumn) = Application.VLookup(.Cells(rw, 2).Value2, col, 2, False)
    Next rw
End With

End Sub

错误:

Set col = Workbooks(MySourceSheet).Sheets("Documents to be reviewed").Range("A:B")

吐出

  

运行时错误'9'(下标超出范围)

但是,当我将courser移到MySourceSheet上时,它会显示模块中前面定义的正确工作簿。如果我使用.xls扩展名手动输入工作簿的名称,它完全正常。我试图在整个网络上寻找答案,但没有什么能解决它。我非常感谢一些帮助! :)

0 个答案:

没有答案