简体   繁体   中英

How do I avoid subscript out range error 9 when copying workbook with dynamic names?

I keep getting error 9 when I try to import a sheet from another workbook to my current workbook.

This is my code. It keeps highlighting the last row in yellow. I'm trying to copy a sheet called sheet1 from a workbook called MB_OP Report_Today'sDate to the workbook AEM_WK_current week .

Sub InQltyMB_1()
    ' InQlyMB Macro
    ' Imports the MB sheet
     For WeekNum = 40 To 2500
        szToday = Format(Date, "MM.D.YYYY")
        Windows("MB_OP Report_" & szToday & ".XLS").Activate
        Sheets("Sheet1").Select
        Sheets("Sheet1").Copy Before:=Workbooks("AEM_WK_" & WeekNum & ".xlsx").Sheets(1)
    Next WeekNum
End Sub

Create variables for your attribuitions, avoid the use of Activate, Select and events in general.

In order to work I just created workbooks variables and remove the activate logic

    Sub InQltyMB_1()
      '
      ' InQlyMB Macro
      ' Imports the MB sheet
    Dim wbReport As Workbook
    Dim wbAEM_WK As Workbook
    
    For WeekNum = 40 To 2500
        
        szToday = Format(Date, "MM.D.YYYY")
        
        Set wbReport = Workbooks("MB_OP Report_" & szToday & ".XLS")
         
        Set wbAEM_WK = Workbooks("AEM_WK_" & WeekNum & ".xlsx")
         
        wbReport.Sheets(1).Copy Before:=wbAEM_WK.Sheets(1)
        
        'Maybe if you won't use the workbooks you could close them, uncomment bellow rows for close
        'wbReport.Close
        'wbAEM_WK.Close
        
    Next WeekNum
    
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM