![](/img/trans.png)
[英]Macro to create activex command button and assign a macro to that button
[英]Excel macro to create a command button and assign macro to the 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
來創建各種按鈕,但是它不能正常工作,因為所有選定的選項都顯示相同的按鈕,並且該按鈕也不會消失。 另外,我似乎無法為創建的按鈕分配宏。
這只是以下示例:
。
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
如果我正確理解了該問題,則希望在工作表上有一個下拉列表(組合框),並且單擊按鈕時,要根據選擇運行宏。 下面是這樣做的-看看是否對您有幫助。
首先-創建一個組合框,並為輸入(組合框中的名稱)和輸出(選定值)創建一個范圍。 例如,您可以調用輸入selectionIn
和結果selectionOut
。
確切步驟:
在E1:E4中寫入組合框選擇的值。 選擇四個單元格,然后在名稱框中(在編輯欄的左側)鍵入selectionIn
。 這將創建一個命名范圍(還有其他創建命名范圍的方法,但這是我的首選方法)。
稱為單元格F1
selectionOut
創建了一個組合框,並為其輸入和輸出引用了這兩個范圍:
創建一個按鈕,給它加上標簽“ Go”,並將其鏈接到動作runIt
。
最后,我在工作簿模塊中創建了以下代碼:
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
這顯示了根據選擇的內容處理不同案件的幾種不同方式。 當然,每次更改組合框選擇時,您都可以運行一個宏-但是從您的描述中聽起來好像不是您想要的。
讓我知道您如何看待此代碼示例-我試圖保持簡單,但同時顯示一些選項。
一種替代方法(可能更簡單)是使用包含您要調用的函數名稱的數組:
Sub otherMethod()
Dim functionList()
functionList = Array("caseOne", "caseTwo", "caseThree", "caseFour")
Application.Run functionList([selectionOut].Value - 1)
End Sub
這當然是我想到的最緊湊的方法...您需要偏移量-1
因為數組索引是以0為基數(無論如何默認情況下),並且組合框為第一個選擇返回1
。 您可以通過編寫代碼使代碼更健壯
functionIndex = [selectionOut].Value + LBound(functionList) - 1
Application.Run functionList(functionIndex)
這樣可以確保,如果將functionList
數組的基本索引更改為另一個值,則所有索引仍將正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.