首页 > 解决方案 > 从用户表单返回一个值

问题描述

我正在尝试将用户窗体中的值返回到另一个宏。

这是我要返回值的一段代码示例intMonth

sub comparison()
    UserForm1.Show
end sub

然后我有用户表单代码:

Private Sub initialize()
    OptionButton1 = False
End Sub

Private Sub OptionButton1_Click()
    intMonth = 1
    Me.Hide
End Sub

如何将intMonth1恢复到原始comparison()功能?

标签: excelvbauserform

解决方案


这是一个最小的例子,但应该有所帮助。

用户窗体的屏幕截图

在用户窗体中:

Option Explicit
Option Base 0

Public intMonth As Long    ' <-- the variable that will hold your output

Private Sub initialize()
    OptionButton1 = False
    intMonth = 0
End Sub

Private Sub CommandButton1_Click()  ' OK button
    Me.Hide
End Sub

Private Sub OptionButton1_Click()
    intMonth = 1    '<-- set the value corresponding to the selected radio button
End Sub

Private Sub OptionButton2_Click()
    intMonth = 2
End Sub

在一个模块中或ThisWorkbook

Option Explicit
Option Base 0

Sub comparison()
    UserForm1.Show
    MsgBox CStr(UserForm1.intMonth)   ' <-- retrieve the value
End Sub

推荐阅读