【问题标题】:access value class module in another sub访问另一个子中的值类模块
【发布时间】:2013-06-07 16:01:22
【问题描述】:

我需要以下方面的帮助。我制作了一个名为 CMpos 的类模块:

Public secId As String

然后在一个模块中,以下代码运行良好:

   Sub testclass()

rijaantal_LenDump = Application.CountA(Sheets("Len_Dump").Range("A:A"))
kolomaantal_LenDump = Application.CountA(Sheets("Len_Dump").Range("1:1"))

Sheets("Len_Dump").Select
positions = Sheets("Len_Dump").Range(Cells(1, 1), Cells(rijaantal_LenDump, kolomaantal_LenDump))


kolomSecID = 8

Dim isc As New Collection

For i = 1 To rijaantal_LenDump
Set psecs = New CMpos
psecs.secId = CStr(positions(i, 8))
If Not Exists(isc, psecs.secId) Then isc.Add psecs, psecs.secId
Next i

Debug.Print isc.Count

MsgBox isc(8).secId

End Sub

现在我想从另一个 sub 访问类 Moldule 中的值,但在这里我在 MsgBox isc(8).secId (type mismatch) 行上遇到错误。我在一个单独的模块中使用 Public isc As Collection 行创建了一个 Globale 变量。

Sub hjhk()
Call testclass
Dim isc As CMpos

Set isc = New Collection


MsgBox isc(8).secId
End Sub

我做错了什么?

谢谢 阿米尔

【问题讨论】:

  • isc in testClass 在 sub 结束后立即超出范围。您需要将其声明为testClass 之外的全局变量。或者将testClass 转换为返回它创建的集合的函数。
  • 嗨蒂姆,我试过了。我将 isc 声明为 testclass 外部的全局变量,如下所示:public isc as Collection。还有其他问题。
  • hjhk 中,您正在创建一个具有本地范围的全新集合对象isc。这没有内容,所以尝试访问isc(8) 会失败...
  • 好的,但是如何在 sub hjhk 的 sub testclass 中访问集合?

标签: excel class vba global-variables


【解决方案1】:
Dim isc as Collection 'global variable

Sub testclass()

    Dim psecs as CMpos

    Set isc = New Collection 'isc refers to the global variable,
                             '  so no need to declare it here

    For i = 1 To 8
        Set psecs = New CMpos
        psecs.secId = "Test-" & i
        isc.Add psecs, psecs.secId
    Next i
End Sub

Sub Test2()
    testClass
    Debug.Print isc(8).secId 'sic is declared as global, so no need to declare/create
End Sub

【讨论】:

  • 蒂姆,它现在可以工作了。您能否解释一下需要:Dim pssecs as CMpos 和 Set isc = New Collection。我使用 -> Dim isc As New Collection。为什么这不起作用,有什么区别?谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2017-10-26
  • 2015-03-10
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多