OK so, I know I can do this:
Dim ws as worksheet
Set ws = thisworkbook.worksheets("Sheet1")
and then do my fancy stuff with the ws
worksheet object
I also know I can Dim wss as worksheets
and that using worksheets("Sheet1")
returns the worksheet object. So why doesn't the following work?
Dim wss as worksheets
Dim ws as worksheet
Set wss = thisworkbook.worksheets
Set ws = wss("Sheet1")
I've also tried:
Dim wss as worksheets
Dim ws as worksheet
Set ws = thisworkbook.wss("Sheet1")
but the latter just looks like I'm trying to rename/shorten "worksheets" which seems totally wrong. I'm trying to get the worksheets of a workbook in to one worksheets object called wss. This is more about trying to understand the heirachy than anything but for functional purposes I'm trying to get wss to encompass all worksheets from workbook x so I could just do ws = wss(1)
instead of saying set ws = wb.worksheets(1)
Is that even possible or am I misunderstanding the worksheets/ worksheet relationship?
you must declare wss
as a Sheets object
Dim wss As Sheets
Dim ws As Worksheet
Set wss = ThisWorkbook.Worksheets
Set ws = wss("Sheet1")
this is because Worksheets property of Workbook
object returns a Sheets
collection, ie a collection that contains both Worksheets
and Charts
object of the workbook
Should you need a collection of your Workbook
Worksheets
only (not Charts
) to be called like ws = wss(1) or the likes then you could adopt the following workaround with Collection
object
Option Explicit
Sub main()
Dim wss As Collection
Dim ws As Worksheet
Set wss = GetWorkSheets
Set ws = wss("Sheet1")
Set ws = wss(1)
End Sub
Function GetWorkSheets() As Collection
Dim wss As New Collection
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
wss.add ws, ws.Name
Next ws
Set GetWorkSheets = wss
End Function
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.