好的,我知道我可以这样做:
Dim ws as worksheet
Set ws = thisworkbook.worksheets("Sheet1")
然后用ws
工作表对象
我也知道我可以Dim wss as worksheets
并且使用worksheets("Sheet1")
返回工作表对象。那么为什么不进行以下工作呢?
Dim wss as worksheets
Dim ws as worksheet
Set wss = thisworkbook.worksheets
Set ws = wss("Sheet1")
我也尝试过:
Dim wss as worksheets
Dim ws as worksheet
Set ws = thisworkbook.wss("Sheet1")
但后者看起来像我试图重命名/缩短"工作表"这看起来完全错了。我试图将工作簿的工作表放到一个名为wss的工作表对象中。这更多的是试图理解heirachy而不是为了功能目的,我试图让wss包含来自工作簿x的所有工作表,所以我可以ws = wss(1)
而不是说set ws = wb.worksheets(1)
< / p>
这是可能的还是我误解了工作表/工作表的关系?
答案 0 :(得分:12)
您必须将wss
声明为Sheets对象
Dim wss As Sheets
Dim ws As Worksheet
Set wss = ThisWorkbook.Worksheets
Set ws = wss("Sheet1")
这是因为Workbook
对象的Worksheets属性返回Sheets
集合,即包含工作簿的Worksheets
和Charts
对象的集合< / p>
如果您只需要Workbook
Worksheets
的集合(不是Charts
)来调用ws = wss(1)或类似内容,那么您可以采用以下解决方法: Collection
对象
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