Excelmacros创build一个命令button并将macros指定给该button

我正在为我的成本计算模型build立一个主页。 在这个页面上,我使用combobox创build了一个下拉列表,然后我想分配一个macros,一旦从列表中select了一个选项,就会创build一个不同button/命令button的列表。 然后,我想要build立另一个分配给这些button的macros,然后根据他们从下拉菜单中select的选项,把用户带到同一工作簿中的另一个选项卡/工作表。

有人可以给我一个想法,我应该使用什么代码,首先创build一个命令button,从下拉列表中select的选项,然后分配一个简单的macros到该button,然后带我到指定的选项卡/片?

到目前为止,我有以下几点:

Option Explicit Sub Select_Change() With ThisWorkbook.Sheets("Main Page").Shapes("Select").ControlFormat Select Case .List(.Value) Case "Vehicle1": All_States1 Case "Vehicle2": All_States2 Case "Vehicle3": All_States3 Case "Vehicle4": All_States4 Case "Vehicle5": All_States5 Case "Vehicle6": All_States6 Case "Vehicle7": All_States7 End Select End With End Sub 

然后,我尝试使用名称All_States1创build各种button,但它不能正常工作,因为所有选定的选项都显示相同的button,并且button也不会消失。 此外,我似乎无法分配一个macros创build的button。

如果我正确地理解了这个问题,你希望在工作表上有一个下拉菜单(combobox),当点击一个button时,你想要根据select运行一个macros。 以下是 – 看看它是否有帮助。

首先 – 为input(combobox中的名称)和输出(所选值)创build一个combobox和一个范围。 例如,您可以调用inputselectionIn和结果selectionOut

在这里输入图像描述

准确步骤:

在E1:E4中写下comboboxselect的值。 select四个单元格,然后在名称框(在编辑栏左侧)中键入selectionIn 。 这将创build一个命名范围(还有其他方法来创build命名范围,但这是我的首选方法)。

称为单元格F1 selectionOut

创build了一个combobox,并为其input和输出引用了这两个范围:

在这里输入图像描述

创build一个button,给它的标签“去”,并将其链接到行动runIt

最后,我在工作簿模块中创build了以下代码:

 Sub runIt() Dim whatToDo, makeName As Boolean ' look up the name of the combo based on the value: whatToDo = Range("selectionIn").Cells([selectionOut].Value, 1) MsgBox "have to do '" & whatToDo & "'" makeName = False Select Case whatToDo Case "one" ' example of putting the code you need right in the select: MsgBox "doing the first thing" Case "two" ' example of calling a specific routine: Call caseTwo Case "three" Application.Run "case" & whatToDo ' making the name of the function on the fly Case "four" makeName = True End Select If makeName Then Dim nameToRun nameToRun = "case" & whatToDo Application.Run nameToRun End If End Sub Sub caseTwo() MsgBox "called the code for case two" End Sub Sub caseThree() MsgBox "doing case three here" End Sub Sub caseFour() MsgBox "even four can be done" End Sub 

这显示了根据所选内容处理不同情况的几种不同方法。 当然,每当comboboxselect被改变时,你都可以运行一个macros – 但是从你的描述中听起来并不是你想要的。

让我知道你如何继续这个代码示例 – 我试图保持简单,但同时显示一些选项。

一个替代scheme(可能更简单)将是一个数组,其中包含要调用的函数的名称:

 Sub otherMethod() Dim functionList() functionList = Array("caseOne", "caseTwo", "caseThree", "caseFour") Application.Run functionList([selectionOut].Value - 1) End Sub 

这当然是我可以想到的最紧凑的方法…你需要-1的偏移量,因为数组索引是基数0(默认情况下),combobox为第一个select返回1 。 你可以通过编写使你的代码更健壮

 functionIndex = [selectionOut].Value + LBound(functionList) - 1 Application.Run functionList(functionIndex) 

这可以确保,如果您将functionList数组的基本索引更改为另一个值,它将仍然正常工作。

这只是一个例子:

  1. 创build一个button
  2. 给它分配一个macros

 Sub button_maker() Dim r As Range Set r = Selection ActiveSheet.Buttons.Add(94.5, 75.75, 51, 27.75).Select With Selection .OnAction = "mooney" .Characters.Text = "Bump" End With r.Select End Sub Sub mooney() Range("A1").Value = Range("A1").Value + 3 End Sub