【发布时间】:2012-07-30 18:14:24
【问题描述】:
这真的难倒我。我昨天提出了一个关于模块之间传递集合的问题(see here),但我似乎没有得到更多关于那个的解释,所以我试图以一种通用的方式更清楚地重申这个问题。
我有一个模块 (module1) 和一个用户表单 (userform1)。我在 userform1 中创建了一个集合(或数组)并将工作表对象添加到该数组中。然后我将控制权传递给 module1,它调用 userform1 中名为 addNewFile 的子程序,它应该将新创建的工作簿添加到集合中。但是,每次 module1 调用 addNewFile 时,我都会遇到以下两种情况之一:1)集合已被删除,所有已添加的工作表现在都消失了(对于集合),2)我收到一条错误消息,指出我的类型不匹配(对于一个数组)。我不知道为什么会这样,所以下面的代码可以更好地说明。任何帮助都将不胜感激,即使只是告诉我无法将工作表对象存储在数组中。
用户窗体1
Dim workBooksCollection as New Collection 'can also define as an array
Private Sub CommandButton1_click()
Dim mainWorkBook as workbook
Set mainWorkBook = ActiveWorkbook
Dim testwb As Workbook
workBooksCollection.Add Item:=mainWorkBook, key:="main" 'Adds successfully
workBooksCollection.Add Item:=testwb, key:="test" 'Adds successfully
MsgBox "the size of the array is: " & usedWorkBooks.Count 'Prints off as size 2
Module1.initialize
'After running initialize, prints off as size 0, meaning collection has been erased
MsgBox "the size of the array is: " & usedWorkBooks.Count 'Prints off as size 0
End Sub
Public Sub addNewFile(filepath As String, sheetKey As String)
Dim newWorkBook As Workbook
Set newWorkBook = Workbooks.Open(filepath)
MsgBox "The name of the workbook is: " & newWorkBook.name 'Prints off name of workbook successfully
workBooksCollection.Add Item:=newWorkBook, key:=sheetKey
MsgBox "the size of the array is: " & workBooksCollection.Count 'Prints off as size 1
End Sub
模块1
Public Sub intialize()
Dim filepath as string
'The filepath is set to any path of a workbook
'This will print out that the array size is 1
UserForm1.addNewFile filePath, "secondBook"
End Sub
对不起,如果我似乎在这里打败了一匹死马,但我真的不知道这里发生了什么。我习惯于集合和列表是全局的并且在被另一个模块引用时不会改变的想法。任何关于这里发生的事情的帮助都会很棒。
【问题讨论】:
-
此外,所有数据类型都会发生这种情况,而不仅仅是工作簿。
-
您似乎没有初始化您的
workBooksCollection集合对象 (Set workBooksCollection =New collection)。这是在哪里发生的? -
抱歉,我忘记在 workBooksCollection 之前添加 New 运算符。它现在显示为
Dim workBooksCollection as New Collection -
你的表格是怎么显示的?
-
目前我只是在 Excel 的开发人员环境中运行它。我还没想好我想怎么展示它。
标签: vba excel automation office-automation