【问题标题】:VBA: Problem with passing arguments to userformVBA:将参数传递给用户表单的问题
【发布时间】:2019-09-19 05:57:32
【问题描述】:

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

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

我尝试了以下方法:

  • 直接在用户表单中计算

  • 全局变量

这没有奏效:

  • 将用户表单声明为变量并使用该变量

  • [Public|Private|Friend] Property Let (ByRef|ByVal) 的所有可能组合

  • Property Set 在任何情况下都不起作用

我的主(模块)代码

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

对象变量或未设置块变量

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

需要对象(错误 424)

【问题讨论】:

  • Property Let counter()中去掉Set
  • 我想我明白了..._initialize 的时刻还早,此时.counter 没有设置,Property Let counter() 我不必设置@987654331 @,这就是丢弃错误的原因。使用_activate 它可以工作。明天我将在办公室尝试我的现场节目,这只是一个短暂的重建。

标签: vba properties userform


【解决方案1】:
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 指令返回时运行,但在对象引用被提供给 With 块之前(请注意,这适用于任何类,而不仅仅是表单) - 那是在.counter = 3 分配之前!根据经验,您希望在该处理程序中初始化实例状态,而不是使用它。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多