VBA: Opening a worksheet by variable name

2019-09-12 10:28发布

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

1条回答
孤傲高冷的网名
2楼-- · 2019-09-12 11:04

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));
查看更多
登录 后发表回答