2014-02-06 82 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 
相關問題