VBA运行时错误'91'-收集工作表名称

时间:2020-11-11 10:00:00

标签: vba

我正在尝试创建一个子目录,该子目录将生成工作簿中所有工作表的集合。到目前为止,我的代码是:

Sub collMaker()

Dim coll As Collection, ws As Worksheet, x As String

For i = 2 To Application.Sheets.count
     x = Application.Sheets(i).name
     coll.Add Item:=x, Key:=x
Next i

End Sub

当我运行它时,我在coll.add行上总是遇到运行时错误。我试图找出为什么会这样,但是我没有发现任何有意义的东西。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

创建集合时需要使用New,否则它将被定义为Nothing,并且您一无所获。

Dim所有变量也是一个好主意。

Sub collMaker()

Dim coll As New Collection, ws As Worksheet, x As String
Dim i As Integer

For i = 2 To Application.Sheets.Count
     x = Application.Sheets(i).Name
     coll.Add Item:=x, Key:=x
Next i

End Sub

What does the keyword 'New' do in VBA?