I'm trying to write a VBA macro to import a sheet from another workbook. I get a "subscript out of range" error on the "copy" line. The file opens correctly, but I'm not sure what goes wrong after that.
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim lastdate As String, filename As String
lastdate = Format(sheet_1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Workbooks.Open (filename)
Workbooks(filename).Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
Workbooks(filename).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = False
End Sub
Edit: error changed to "subscript out of range", code changed so worksheets referenced by index.
Code v2:
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim lastdate As String, filename As String
lastdate = Format(sheet1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Dim wbk As Workbook
wbk = Workbooks.Open(filename)
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
wbk.Close
End Sub
sheet_3
andsheet_1
dimensioned and what datatype and values are they? – user2140173Application.DisplayAlerts = True
at the end. Plus, you should always do error handling when setting that toFalse
else you're headed for bad surprises fast. – Jean-François CorbettApplication.DisplayAlerts
. according to Help, "If you set this property to False, Microsoft Excel sets this property to True when the code is finished, unless you are running cross-process code." – Mark Fitzgerald