这真的让我很难过。我昨天提出了一个问题,关于模块之间传递的集合(see here),但似乎我没有得到关于那个的解释,所以我试图以一般方式更清楚地重述问题
我有一个模块(module1)和一个userform(userform1)。我在userform1中创建一个集合(或数组),并将工作表对象添加到此数组。然后我将控制传递给module1,它调用userform1中名为addNewFile的sub,它应该将新创建的工作簿添加到集合中。但是,每次module1调用addNewFile时,我都会得到以下两种情况之一:1)集合已被删除,所有已添加的工作表现已消失(对于集合),2)我收到一条错误消息,说我的类型不匹配(对于数组)。我不知道为什么会这样,所以下面的代码更好地说明了。任何帮助都会受到赞赏,即使它只是告诉我无法将工作表对象存储在数组中。
UserForm1
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
对不起,如果我好像在这里打死马,但我真的不知道这里发生了什么。我习惯于集合和列表的概念是全局的,并且在被另一个模块引用时不会改变。任何关于这里发生的事情的帮助都会很棒。
答案 0 :(得分:2)
我想发表评论,但我不能,因为我不得不重做我的帐户,因为我被锁定了我的原件。
如果我的回答没有帮助,我会稍微删除一下,但如果你更换了什么 -
Dim workBooksCollection as collection 'can also define as an array
从UserForm模块进入模块1:
Public workBooksCollection as collection 'can also define as an array
有帮助吗?