vba 将宏分配给组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26479840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:55:55  来源:igfitidea点击:

Assigning macros to a combobox

vbacombobox

提问by Arjun Singh

I have been trying to assign 3 macros to a dropdown menu.

我一直在尝试将 3 个宏分配给下拉菜单。

I created a combobox using Developer > Insert > ComboBox (not ActiveX controls) with three options: "Table 1", "Table 2" and "Table 3". Now, I want to assign a macro to each of those three options. If "Table 1" is clicked, then macro1would run; if "Table 2 " then macro2, etc.

我使用开发人员 > 插入 > 组合框(不是 ActiveX 控件)创建了一个组合框,其中包含三个选项:“表 1”、“表 2”和“表 3”。现在,我想为这三个选项中的每一个分配一个宏。如果单击“表 1”,则macro1运行;如果“表 2”那么macro2,等等。

I was able to create a menu through right clicking > Format Control and then choosing an input range.

我能够通过右键单击> 格式控制然后选择输入范围来创建菜单。

But how do I link the dropdown options to macros?

但是如何将下拉选项链接到宏?

回答by Jean-Fran?ois Corbett

You want to assigna macro to the combobox.

您想为组合框分配一个宏。

  1. Open a module and write a macro called e.g. DropDown1_Change().
  2. Right-click the combobox > Assign Macro... select your macro in the list > OK.
  1. 打开一个模块并编写一个名为 eg 的宏DropDown1_Change()
  2. 右键单击组合框 > 分配宏... 在列表中选择您的宏 > 确定。

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

The assigned macro should determine which dropdown option was clicked, and call a different macro based on that choice. It could look something like this:

分配的宏应确定单击了哪个下拉选项,并根据该选择调用不同的宏。它可能看起来像这样:

Sub DropDown1_Change()
    Dim c As ControlFormat
    Set c = Sheet1.Shapes("Drop Down 1").ControlFormat ' or whatever yours is called

    'Choose which macro to run based on the selected value in the combobox
    Select Case c.Value
    Case 1: Macro1
    Case 2: Macro2
    Case 3: Macro3
    End Select
End Sub

Sub Macro1()
    MsgBox "Macro 1"
End Sub
Sub Macro2()
    MsgBox "Macro 2"
End Sub
Sub Macro3()
    MsgBox "Macro 3"
End Sub