VBA: 将参数传递给用户窗体时出现问题

VBA: Problem with passing arguments to userform

我已经搜索并尝试了6个小时,还是无法解决问题。

我的想法: 我想在 Excel-VBA 中显示一个带有一些单选按钮、一个列表元素和一个文本字段的用户表单。 我想将一些参数传递给用户窗体以使用它,因为我不想在用户窗体代码内部进行计算(有效) 我也不想声明全局变量。

我尝试了以下有效的方法:

这没有用:

来自我的主要(模块)的代码

Option Explicit

Sub main()
    With New usr_mainInput
        .counter = 3
        .Show
    End With
End Sub

我在用户表单中的代码

Option Explicit

Private miCounter As Integer

Property Get counter() As Integer
    counter = miCounter
End Property
Property Let counter(c As Integer)
    Set miCounter = c
End Property

Private Sub userform_initialize()
    Dim i As Integer
    For i = 1 To counter           'miCounter don't work as well
        Debug.Print i
    Next i
End Sub

Private Sub btn_ok_Click()
    Me.Hide
End Sub

未设置对象变量或 With 块变量

如果涉及到 Property Let counter(),它会抛出一个编译错误:

Object required (Error 424)

Property Let counter(c As Integer)
    Set miCounter = c
End Property

对象是必需的,只是因为 Set 关键字。这不是引用赋值,而是值赋值。

这样看:

Property Let counter(c As Integer)
    Let miCounter = c
End Property

只是不要实际输入 Let 关键字(它 起作用),it's obsolete :)

另请注意,Property Let/Set 过程参数的隐式修饰符始终是 Byval - 这与 VBA 中的任何其他内容不同,其中隐式修饰符是 ByRef;考虑使 ByVal 修饰符显式化。


Private Sub userform_initialize()
    Dim i As Integer
    For i = 1 To counter           'miCounter don't work as well
        Debug.Print i
    Next i
End Sub

那个循环永远不会迭代任何东西,因为 Initialize 处理程序 运行 在这里:

With New usr_mainInput

我的意思是,当 New usr_mainInput 指令 returns、 但在将对象引用提供给 With 块之前 运行s =49=](请注意,这对任何 class 都是正确的,而不仅仅是形式)- 这远远早于 .counter = 3 赋值!根据经验,您希望在该处理程序中 初始化 实例状态,而不是使用它。

考虑改用 Activate 处理程序。在 .Show 调用后立即 运行。