这真的难倒我。我昨天提出了一个关于在模块之间传递集合的问题(见这里),但我似乎没有得到更多关于那个的解释,所以我试图以一种通用的方式更清楚地重申这个问题。
我有一个模块(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
抱歉,如果我似乎在这里打败了一匹死马,但我真的不知道这里发生了什么。我习惯于集合和列表是全局的并且在被另一个模块引用时不会改变的想法。对这里发生的事情的任何帮助都会很棒。