简体   繁体   English

Excel VBA-将UserForm ComboBox中的值分配给全局变量

[英]Excel VBA - Assign value from UserForm ComboBox to Global Variable

I have a userform with a basic combobox and command button. 我有一个带有基本组合框和命令按钮的用户窗体。 When the user hits the command button, I want the UserForm to close, and the value of the combobox to be saved in a variable that can be accessed by a subroutine contained within "ThisWorkbook". 当用户单击命令按钮时,我希望关闭UserForm,并将组合框的值保存在一个变量中,该变量可由“ ThisWorkbook”中包含的子例程访问。

In the UserForm code: 在用户窗体代码中:

Public employee_position As String    
Public Sub CommandButton1_Click()

    employee_position = Me.ComboBox1.Value
    Unload Me

End Sub

In the "ThisWorkbook" Code 在“ ThisWorkbook”代码中

Private Sub GetUserFormValue()
    Call Userform_Initialize
    EmployeePosition.Show
    MsgBox employee_position
End Sub

When "GetUserFormValue()" runs, the UserForm comes up, you can select a value in the combobox and press the command button, but when the MsgBox comes up, it displays "" (Nothing) 当“ GetUserFormValue()”运行时,出现用户窗体,您可以在组合框中选择一个值并按命令按钮,但是当MsgBox出现时,它显示“”(无)

What am I doing wrong here? 我在这里做错了什么?

When you Unload Me , I think you lose all information associated with the module (including the global variable). 当您“ Unload Me ,我认为您会丢失与模块关联的所有信息(包括全局变量)。 But if you use Me.Hide rather than Me.Unload, then you can access the value of the form after the routine returns. 但是,如果您使用Me.Hide而不是Me.Unload,则可以在例程返回后访问表单的值。 So try this: 所以试试这个:

-- userform code includes: -用户表单代码包括:

Public Sub CommandButton1_Click()
    Me.Hide
End Sub

-- main module includes: -主要模块包括:

Private Sub GetUserFormValue()
    Call Userform_Initialize
    EmployeePosition.Show
    MsgBox EmployeePosition.ComboBox1.Value
    Unload EmployeePosition
End Sub

I think that should work. 我认为应该可以。

I had the same problem, and this is how I resolved it: 我遇到了同样的问题,这就是我的解决方法:

If the main code is in a worksheet, and the variable is declared as public in that worksheet (eg in Microsoft Excel Objects -> Sheet1 (Sheet1)), the result from "Unload Me" cannot be passed from a UserForm to the worksheet code. 如果主代码在工作表中,并且该变量在该工作表中被声明为公共变量(例如,在Microsoft Excel对象-> Sheet1(Sheet1)中),则无法将“卸载我”的结果从UserForm传递到工作表代码。

So to solve my problem, I inserted a new Module, and declared my public variable there. 因此,为了解决我的问题,我插入了一个新的Module,并在其中声明了我的公共变量。 I didn't even have to move my code from the worksheet to the module... just the declaration of the public variable. 我什至不必将代码从工作表移至模块中……只需声明公共变量即可。

I hope this works for you too! 我希望这也对您有用!

Andrew 安德鲁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM