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

时间:2014-02-06 18:43:11

标签: excel vba

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

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应用程序/对象定义错误。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

你已经解决了你的问题,但这就是我接近它的方式

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