2014-02-06 66 views
1

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

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应用程序/对象定义的错误...线。任何建议为什么?

+0

当使用'范围'两个范围()和电池() - 如果不是合格与工作表 - 将参考activesheet。您需要为该表达式的所有部分指定工作表。如果您为每个工作表声明一个变量并在使用范围时使用这些引用,而不是始终使用'Workbooks(...)。表格(...)' –

+0

@TimWilliams,谢谢这个建议。我能够成功使用'Range(“A2:E”&LastRow)''。有没有更高效或更干净的方法来做到这一点? – CJK

回答

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 
相关问题