VBA – 从封闭的Excel工作簿中检索数据

我正在尝试创build一个VBA脚本,它将从四个不同的工作簿收集数据。 现在,我只是用一个Workbooktesting代码,但是当我尝试获取数据时,我收到一个错误。 虽然我想从四个工作簿中检索数据而不打开它们,但我需要打开它们才能find最后一行数据。 这是我目前的代码:

Public Sub GetData() Application.ScreenUpdating = False Dim LastRow As Integer Dim WB As Workbook Dim xlsPath As String Dim xlsFilename As String Dim SheetName As String xlsPath = "C:\Users\a27qewt\My Documents\Document Retention\FI_DocumentRetention.xlsm" Set WB = Workbooks.Open(xlsPath) 'Workbooks("FI_DocumentRetention.xlsm").Sheets("S&S Document Locations").Unprotect LastRow = Workbooks("FI_DocumentRetention.xlsm").Sheets("S&S Document Locations").Cells(Rows.Count, "A").End(xlUp).Row Workbooks("SS_Index.xlsm").Sheets("Document Index").Range(Cells(2, 1), Cells(LastRow, 5)).Value = _ Workbooks("FI_DocumentRetention.xlsm").Sheets("S&S Document Locations").Range(Cells(2, 1), Cells(LastRow, 5)).Value WB.Close False End Sub 

我在Workbooks("FI_DocumentRetention.xlsm").Sheets("S&S Document Locations").Range收到1004应用程序/对象定义错误Workbooks("FI_DocumentRetention.xlsm").Sheets("S&S Document Locations").Range 。 任何build议为什么?

你已经解决了你的问题,但这是我的方法

 Public Sub GetData() Dim LastRow As Long '<< not Integer Dim WB As Workbook Dim xlsPath As String Dim xlsFilename As String Dim SheetName As String Dim shtSrc As Worksheet, shtDest As Worksheet, rngSrc As Range Application.ScreenUpdating = False xlsPath = "C:\Users\a27qewt\My Documents\Document Retention\FI_DocumentRetention.xlsm" Set WB = Workbooks.Open(xlsPath) Set shtSrc = WB.Sheets("S&S Document Locations") Set shtDest = Workbooks("SS_Index.xlsm").Sheets("Document Index") LastRow = shtSrc.Cells(shtSrc.Rows.Count, "A").End(xlUp).Row Set rngSrc = shtSrc.Range(shtSrc.Range("A2"), _ shtSrc.Cells(LastRow, 5)) shtDest.Range("A2").Resize(rngSrc.Rows.Count, _ rngSrc.Columns.Count).Value = rngSrc.Value WB.Close False End Sub