【问题标题】:How to pass a variable from a command button action on a user form to a module in Excel VBA [duplicate]如何将变量从用户表单上的命令按钮操作传递到 Excel VBA 中的模块[重复]
【发布时间】:2023-02-01 13:36:50
【问题描述】:
我是董事会的新手。我在 VBA for Excel 中有一个模块和一个带有 4 个命令按钮的关联用户表单。我用frmSelect.Show 调用用户表单。用户将选择 4 个命令按钮中的一个,然后将一个值分配给我要传递给模块的变量。这样我就可以知道哪个 CommandButton 被激活了。我似乎无法弄清楚如何传递变量,因为变量总是作为 null (0) 返回到模块。
这是模块代码:
Sub BumpGenerator()
Dim Pattern As Integer
frmSelect.Show
If Pattern = 1 then
Do some stuff
End If
If Pattern = 2 then
Do some other stuff
End If
If Pattern = 3 then
Do some other stuff
End If
If Pattern = 4 then
Do this stuff
End If
End Sub
这是用户表单中的代码:
Private Sub CommandButton1_Click()
Pattern = 1
frmSelect.Hide
End Sub
Private Sub CommandButton2_Click()
Pattern = 2
frmSelect.Hide
End Sub
Private Sub CommandButton3_Click()
Pattern = 3
frmSelect.Hide
End Sub
Private Sub CommandButton4_Click()
Pattern = 4
frmSelect.Hide
End Sub
我试过使用:
-
我的模块上方的“公共模式作为整数”
-
使用“BumpGenerator(Pattern As Integer)”将 Pattern 作为变量传递
-
在用户表单中使用“Call BumpGenerator(Pattern)”
-
使用“BumpGenerator 值:=模式”
但这些选项都没有改变我的空值。
感谢您的任何回复
【问题讨论】:
标签:
vba
global-variables
userform
【解决方案1】:
表单只是一种特殊类型的类,因此您可以用表单做任何您可以用类做的事情。
在您的用户窗体中定义一个 UDT,它包含您的模块级变量的值。
Private Type State
Pattern as Long
End Type
Private s as State
Private Sub CommandButton1_Click()
s.Pattern = 1
Me.Hide
End Sub
Private Sub CommandButton2_Click()
s.Pattern = 2
Me.Hide
End Sub
Private Sub CommandButton3_Click()
s.Pattern = 3
Me.Hide
End Sub
Private Sub CommandButton4_Click()
s.Pattern = 4
Me.Hide
End Sub
Public Property Get Pattern() as long
Pattern = s.Pattern
End Property
' and then in your module
Sub BumpGenerator()
frmSelect.Show
' You don't lose access to the form just because you've hidden it.
Select Case frmSelect.Pattern
Case 1
Do some stuff
Case 2
Do some other stuff
Case 3
Do some other stuff
Case 4
Do this stuff
End Select
End Sub
顺便说一下,您应该知道您犯了一个典型的新手错误,因为您使用的是 frmSelect 的默认实例,而不是创建表单的特定实例。这就是您可以使用 frmSelect.Hide 而不是 Me.Hide 的原因。
创建自己的表单实例(从长远来看)要好得多。
Dim mySelect as frmSelect
Set mySelect = New frmSelect
etc....
我还建议您为 VBA 安装免费且出色的 Rubberduck 插件,并注意代码检查
【解决方案2】:
如果您声明变量 Pattern global,那么您的代码就可以工作。
我还建议看一下 vba 的 scoping rules。
- 用户表单模块
Option Explicit
Private Sub CommandButton1_Click()
Pattern = 1
BumpGenerator
End Sub
Private Sub CommandButton2_Click()
Pattern = 2
BumpGenerator
End Sub
Private Sub CommandButton3_Click()
Pattern = 3
BumpGenerator
End Sub
Private Sub CommandButton4_Click()
Pattern = 4
BumpGenerator
End Sub
- 标准模块
Option Explicit
Global Pattern As Integer
Sub BumpGenerator()
Debug.Print Pattern
frmselect.Hide
End Sub