如果在VBA中创建一个具有相同名称的新实例,该怎么办?

时间:2019-06-18 09:59:33

标签: excel vba oop

我有一个叫assetTransfer的课。 如果我有一个循环,并且创建了一个具有相同名称的新实例,那么“旧”实例会怎样?

For i = 1 to 10
   Dim assetTransfer as New assetTransfer
next

我会丢失以前的实例吗?

1 个答案:

答案 0 :(得分:2)

在您的情况下,assetTransfer永远不会被实例化,因为它从未被调用。 MS Docs

在大多数情况下,应避免使用dim foo as new bar语句,而应使用单独的声明和实例化,例如:dim foo as barset foo = new bar 原因:What's the difference between Dim As New vs Dim / Set

解决此问题的方法如下所示。
最后,您的收藏夹中有10个assetTransfer实例

dim aCollection as Collection
set aCollection = new Collection
Dim assetTransferInstance as assetTransfer

For i = 1 to 10
   set assetTransferInstance = new assetTransfer
   'do something with assetTransfer
   aCollection.Add assetTransferInstance 
next i

debug.print aCollection.Count   '10