简体   繁体   中英

VBA: Opening a worksheet by variable name

I'm intending to copy some values from a workbook which I import from a folder on my computer, from the worksheet "2015".

My code looks like this:

   Sub test()
   Dim myHeadings() As String
   Dim p3file As String
   Dim currentWb As Workbook
   Dim openWb As Workbook
   Dim openWs As Worksheet

    Set currentWb = ActiveWorkbook
    myHeadings = Split("Januari,Februari,Mars,April,Maj,Juni,Juli,Augusti,September,Oktober,November,December", ",")
    path3 = Dir("C:\pathtofile\filename" & ".xlsx")
    p3file = "C:\pathtofile\" 'Dir doesn't return path
    YearNo = Year(Date)
    Do While Len(path3) > 0
        Set openWb = Workbooks.Open(p3file & path3)
        For i = 0 To UBound(myHeadings)
            Set openWs = openWb.Sheets(YearNo)
            If Err.Number <> 0 Then 'Attempt to exit while loop if sheet does not exist
                Exit Do
            Else
               'Copy a bunch of data
            End if
        Next i
   path3 = Dir("C:\pathtofile\filename" &".xlsx")
   Loop
   Workbooks(openWb.name).Close
   End Sub

I've debugged by making MsgBoxes inside the loop and I can conclude that the program enters the For i = ... loop, but when encountering

    Set openWs = openWb.Sheets(YearNo)

gives "Subscript out of range" error. By doing MsgBoxes I've seen that Dir finds the correct file. "p3file & path3" returns the correct file including path name. I've tested adding "" around YearNo in the opening sheet code. The sheet name is called "2015" (without quotes). Does anyone have any clue regarding this?

Thanks in advance

It's because YearNo is stored as a number, and not as text.

The Sheets Collection asks for either an index number or a string containing the name of the sheet you want to open. In your case you are providing a number, so the code thinks you are asking for sheet with index 2015, hence the out of range error.

You would need to tell Excel that the 2015 you are using is text by converting the number using CStr:-

Set openWs = openWb.Sheets(CStr(YearNo));

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