简体   繁体   中英

Create worksheets object from string

I'm trying to create and object of worksheets that I can iterate through. If I declare it like this, it works :

Set deptSheets = Sheets(Array("Sheet1", "Sheet2", "Sheet3")) 

Instead of explicit comma separated strings, I'd like to feed it a string (let's call it myStringOfSheets) variable that has the same content: "Sheet1", "Sheet2", "Sheet3".

Just swapping it out for a string Set deptSheets = Sheets(Array(myStringOfSheets)) doesn't work because Array() is expecting explicit parameters. I've tried quite a few things, but I'm not having any success if anyone has any ideas please let me know.

Function deptSheets() As Object
    deptSheetsStr = Chr(34) & "Sheet1" & Chr(34) & "," & _
            Chr(34) & "Sheet2" & Chr(34) & "," & _
            Chr(34) & "Sheet3" & Chr(34)
    
   'Set deptSheets = Sheets(deptSheetsStr) <-- also does not work 
    Set deptSheets = Sheets(Split(deptSheetsStr, ",")) 'subscript out of range error on this line

End Function

The following code works. I think the issue was I was declaring deptSheets as an OBJECT not Sheets and likely that my deptSheetsStr was malformed. For some reason I needed to create a separate array - I couldn't get it to work just feeding it a split directly.

    Function deptSheets() As Sheets
        Dim deptSheetsStr As String
        deptSheetsStr = "Sheet1" & "," & "Sheet2" & "," & "Sheet3" & "," & "Sheet4"
        
        Dim sheetArray As Variant
        sheetArray = Split(deptSheetsStr, ",")
        
        
        Set deptSheets = ThisWorkbook.Worksheets(sheetArray)
    End Function

The resulting deptSheets object allows me to loop through the sheets as I desired

For Each wks In lib.deptSheets
    Debug.Print wks.Name
Next

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