Run a Macro from a Drop Down list [VBA]
This article demonstrates how to run a VBA macro using a Drop Down list. The Drop Down list contains two macro names Macro1 and Macro 2, however, you can easily add more if you like.
Table of Contents
1. Run a Macro from a Drop Down list - VBA
Event code makes this possible, it also allows you to open a workbook programmatically when another workbook is opened.
The animated picture below shows a Drop Down list containing two text strings, Macro1 and Macro2. When I select Macro1 in cell B2 a worksheet event code reads the selected value and runs a macro.
The example macros display a message box with the message Macro1 or Macro2 based on the selected value.
Watch this video where I explain how to run a macro from a drop down list
Below are detailed instructions on how I did it.
Create a Drop Down list
A Drop Down list is a Data Validation tool that lets you control what the user can enter in a cell, however, remember that the Drop Down list is not that great in restricting what the user can enter.
For example, you can easily copy a cell and paste it to the cell containing the Drop Down list and Excel won't even warn you.
- Select cell B2.
- Go to tab "Data" on the ribbon.
- Press with left mouse button on the "Data validation" button and a dialog box appears.
- Press with mouse on the Drop Down list below "Allow:" and select "List".
- Type your macro names in Source: field, separated by a comma.
- Press with left mouse button on OK button.
Where to put the event code?
Event code is VBA code that is triggered if a specific thing happens, for example, if a worksheet is selected or a cell is selected, however, there are many many more. The event code is triggered, in this example, if a cell value is changed in worksheet Sheet1.
Remember that the worksheet_change event works only if you put it in a worksheet module, here is how to access a worksheet module:
- Press with right mouse button on on the worksheet name located at the very bottom of your Excel screen and a menu shows up.
- Press with left mouse button on "View code" on that menu, see image below, and the Visual Basic Editor opens with the worksheet module visible for Sheet1.
- The Visual Basic Editor opens. Copy VBA event code below.
- Paste to worksheet module.
- Exit VB Editor (Alt + Q).
VBA Event code
'Event code, Target variable contains the cell or range that has been changed Private Sub Worksheet_Change(ByVal Target As Range) 'Interesect method returns a range object of a rectangular intersection of two or more cell ranges If Not Intersect(Target, Range("B2")) Is Nothing Then 'Select Case statment performs one out of several groups of statements based on a condition Select Case Range("B2") 'If text in cell B2 is equal to Macro1 a macro named Macro1 is rund Case "Macro1": Macro1 'If text in cell B2 is equal to Macro2 a macro named Macro2 is rund Case "Macro2": Macro2 'Stops Select Case statement End Select End If End Sub
Here is the first macro named Macro1, it shows a message box with text "Macro1".
Sub Macro1() MsgBox "Macro1" End Sub
The second macro named Macro2 shows a message box with text "Macro2".
Sub Macro2() MsgBox "Macro2" End Sub
These macros are located in a code module that you need to insert yourself.
Where to put macros?
- Press keyboard shortcut keys Alt + F11 to open the Visual Basic Editor.
- Press with left mouse button on "Insert" on the menu, see image above.
- Press with left mouse button on "Module" to insert a module to your workbook.
- Copy and paste macros to code window.
- Exit VB Editor and return to Excel.
Save your workbook with file extension *.xlsm.
What happens if the Drop Down list is overwritten?
As I mentioned at the beginning of this article Drop Down lists have a major disadvantage, it can easily be overwritten.
For example, copy another cell and paste it to the cell containing a Drop Down list and the Drop Down list is now gone without a warning.
The event code is not even returning an error message, you can, however, add an extra line to the event code that takes care of invalid values.
Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Range("B2")) Is Nothing Then Select Case Range("B2") Case "Macro1": Macro1 Case "Macro2": Macro2 Case Else: MsgBox "Macro not available" End Select End If End Sub
This will not prevent the Drop Down list from being overwritten, it will only return a message telling the Excel user that the value in cell B2 is not valid.
To prevent it from being overwritten you can use the code I found here: Restrict paste into dropdown cells
2. Toggle a macro on/off using a button
This section demonstrates how the user can run a macro by press with left mouse button oning on a button, the text on the button changes based on what the macro has performed. The macro itself reads the button and runs code based on that text.
The animated image above shows a macro that hides and shows checkboxes using only a button. The text on the button shows if they are visible or invisible.
You will in this section learn how to:
- Insert a button (Form Control) on the worksheet
- Change the size of the button.
- Identify button name
- Create a macro
- Manipulate the text on a button programmatically.
- Read button text to determine what VBA lines to run.
- How to start another macro within a macro.
- Assign a macro to a specific button.
- Save the workbook as a macro-enabled workbook.
How to insert a button?
To create a button go to tab "Developer" and press with left mouse button on "Insert" button. Press with mouse on the "button" button and then press and hold with left mouse button on the worksheet.
Now drag with the mouse to create the button, lastly release the left mouse button and the button is now visible on your worksheet.
This allows you to control the size of the button. Don't worry, you can adjust the size later if you didn't get it right.
How to determine the name of a button?
In order to manipulate the button text, you need to know the name of the button. Simply select the button you just created and read the name box.
The dots around the button demonstrated in the picture above tells you that the button is selected, press and hold on one of the dots to change the size of the button.
The name box is located to the left of the formula bar, it contains text "Button 1" without the double quotes in the example image above.
How to toggle button text when you press with left mouse button on the button?
The macro below changes the text shown on "Button 1", this lets you create the toggle effect. It also guides the macro so it knows what lines of code to run.
Make sure you assign this macro to the button you just created, however, first you need to copy the code shown below to a regular code module.
VBA Macro
'Name of macro Sub ToggleMacro() 'Simplify code by refering to object once With ActiveSheet.Shapes("Button 1").TextFrame.Characters 'Check if button text is equal to a specific string. If .Text = "Checkboxes: On" Then 'Change button text. .Text = "Checkboxes: Off" 'This happens if button text is not equal to the specific string. Else 'Change button text. .Text = "Checkboxes: On" End If End With End Sub
Where to put the VBA code?
- Copy VBA code above.
- Press short cut keys Alt+F11 to open the VB Editor.
- Press with left mouse button on "Insert" on the top menu.
- Press with left mouse button on "Module".
- Paste code to module.
- Return to Excel.
How to assign a macro to a specific button?
- Press with right mouse button on on the button and a context menu appears.
- Press with mouse on "Assign Macro..." and the following dialog box shows up.
- Select the macro you want to assign.
- Press with left mouse button on "OK" button.
The selected macro is rund every time the user press with left mouse button ons on the button.
How to toggle checkboxes?
There are two different macros being used that add and delete checkboxes demonstrated here: Add checkboxes to a sheet (1/2)(VBA). Those two macros have to be added to a code module in your workbook in order to make this work.
The macro code below shows how to determine which macro to run by reading the button text displayed on "Button 1". It also shows that the macro is unnecessary long because I am not using the With - With End statement.
VBA Macro
Sub Button1_Press with left mouse button on() If ActiveSheet.Shapes("Button 1").TextFrame.Characters.Text = "Checkboxes: On" Then ActiveSheet.Shapes("Button 1").TextFrame.Characters.Text = "Checkboxes: Off" Call RemoveCheckboxes Else ActiveSheet.Shapes("Button 1").TextFrame.Characters.Text = "Checkboxes: On" Call Addcheckboxes ActiveSheet.Range("A1").Select End If End Sub
3. Use a drop down list to display data in worksheet header - VBA
I have a spreadsheet that I use for 3 different companies. What I would really like to do is have a drop-down menu with the three company names: eg: Mcdonalds, Pizza Hut, Subway and then when I choose which company the spreadsheet will be for then all the contact information and logo will appear as a header on the top of the spreadsheet. Is this possible?
Answer
Yes, it is possible. The animated image above demonstrates a worksheet that allows the user to select a value using a drop-down list and the header changes accordingly. The header and footer are located above and below the cell grid respectively when you print a worksheet.
The drop-down list is a regular drop-down list located in cell C2, the company name and address populates the left header. The zip code and city name populate the center header and the image is displayed on the right header.
If you get the workbook and the images are not showing then you need to create images and save them to c:\temp\ folder or change the paths and file names in column F worksheet Data to the images you want to use.
The following VBA code is event code that is saved to a worksheet module and not a regular module. Adjust cell reference A1:A4 below so it points to all of your data set values.
Event code
The event code below matches the selected company name in the drop-down list to the correct record on sheet "Data", the event macro then saves the row number of that record to a variable and uses that number to extract each value from the record.
Lastly, it saves the data to the header. The header contains three containers, left, center and right. Char(10) is the character for a new line, it separates the company name and address in the left container. It is also used in the center container to put zip code and email address on a line each.
'This event code is rund when a cell value is changed. Private Sub Worksheet_Change(ByVal Target As Range) 'Dimension variables and data types Dim iRow As Single 'Check if target is cell C2 If Not Intersect(Target, Range("C2")) Is Nothing Then 'Enable error handling On Error Resume Next 'Save row number of matching cell in cell range A1:A4 to variable iRow iRow = Application.Match(Range("c2"), Worksheets("Data").Range("A1:A4").Value, 0) 'Check if there has been an error, MATCH function returns an error if no value is found If Err <> 0 Then 'Show a message box MsgBox "Company name not found!" 'Stop event code Exit Sub End If 'Disable error handling On Error GoTo 0 'Save text and picture from data table to header With ActiveSheet 'Save company name and address to left header on active worksheeet .PageSetup.LeftHeader = Worksheets("Data").Range("A" & iRow).Text & Chr(10) & _ Worksheets("Data").Range("B" & iRow).Text 'Save zip code and email address to center header on active worksheeet .PageSetup.CenterHeader = Worksheets("Data").Range("C" & iRow).Text & " " & _ Worksheets("Data").Range("D" & iRow).Text & _ Chr(10) & Worksheets("Data").Range("E" & iRow).Text 'Save picture to right header on active worksheeet .PageSetup.RightHeaderPicture.Filename = Worksheets("Data").Range("G" & iRow).Text End With End If End Sub
Where to put the code?
- Copy code above.
- Press with right mouse button on on sheet name.
- Press with left mouse button on "View code" to open the worksheet module in the VB Editor.
- Paste code to worksheet module.
- Exit vba editor and return to Excel.
Data source
The data set used to populate the header is located on worksheet "Data", the image above shows what the geted file will contain. Column A contains the company names.
Column B contains addresses, column C zip codes, column D city names, column E email addresses and column F contains folder paths and file names to company logos.
Final thoughts
I recommend that you use an Excel defined Table on sheet Data, it allows you to reference only the Table name and table header name. You don't need to adjust cell references when you add records, the Excel defined Table is dynamic.
For example, the following row:
iRow = Application.Match(Range("c2"), Worksheets("Data").Range("A1:A4").Value, 0)
becomes
iRow = Application.Match(Range("c2"), Worksheets("Data").Range("Table1[Company Name]").Value, 0)
Drop down lists category
Table of Contents Create dependent drop down lists containing unique distinct values - Excel 365 Create dependent drop down lists […]
Question: How do I create a drop-down list with unique distinct alphabetically sorted values? Table of contents Sort values using […]
This article demonstrates different ways to reference an Excel defined Table in a drop-down list and Conditional Formatting. There are […]
If then else statement category
Table of Contents Excel monthly calendar - VBA Calendar Drop down lists Headers Calculating dates (formula) Conditional formatting Today Dates […]
This article explains how to hide a specific image in Excel using a shape as a button. If the user […]
Did you know that you can select all cells containing comments in the current sheet? Press F5, press with left […]
Macro category
Table of Contents Excel monthly calendar - VBA Calendar Drop down lists Headers Calculating dates (formula) Conditional formatting Today Dates […]
Table of Contents How to create an interactive Excel chart How to filter chart data How to build an interactive […]
Table of Contents Split data across multiple sheets - VBA Add values to worksheets based on a condition - VBA […]
Excel categories
31 Responses to “Run a Macro from a Drop Down list [VBA]”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
Contact Oscar
You can contact me through this contact form
I need a formula with no Marcos – here an example of what I’m trying to do.
Column A contains:
Head-Phones-Sony
Black-Pen,Skilcraft
AAA-Batteries,24pk
Eraser,5pk
Ink-Pen,Fine-Point-Blue
Column B contains:
M412
M123
M784
M143
M572
In Cell D1 I want to ENTER *Pen* and have it list all corresponding values which is Cell A2 & Cell A5
It sounds like a “Lookup one value with multiple corresponding values” but when I use a wildcard in my search it doesn’t work... Do you have a solution for it? Thank you
Yes, you can use a wildcard in your search. You can use the INDEX and MATCH functions to look up one value with multiple corresponding values. For example, in cell D1 you can use the following formula:
=INDEX($B$2:$B$5,MATCH(“*Mouse*”,$A$2:$A$5,0))
This will return the values from column B that correspond to the cells in column A that contain the keyword “Mouse”. Make sure to use the wildcard “*” before and after the search term in order to get the results you need. Hope this helps!
John Paul,
Read this post:
Search for a text string and return multiple adjacent values
Thanks for commenting!
Thank you. This worked perfectly!
I know this is a little late, but THANK YOU VERY MUCH!!! I have been trying to do this a few different ways via the change event and your method has worked! Love that I can use named ranges as well!! Thanks again!
Excellent. Hats off to you..!!
This took care of the issue I had with Buttons being deleted when they were hidden and saved. Thank you so much as you saved some major time for me..
This worked perfectly for one row in my excel, however, I need to copy this same thing for multiple rows... how do I add to the code?
For example, I have a drop down list with 2 options, each performs a different macro on that same row. (When I recorded the macro, I used relative references in hopes that I could use this same macro on multiple rows...
How do I add this to the VBA Event code?
I need the Event cell, in the example above was B2, to happen in multiple cells in the same column, but only perform that macro on the row that the drop down was changed... is that clear?
Thanks for any help I can get!!
Carolyn,
Have you solved your problem yet? Because im running into the same problem!
Carolyn Vermeulen and Paul van Amelsvoort,
Try this workbook:
Run-a-macro-from-a-drop-down-listv2.xlsm
I need the Event cell, in the example above was B2, to happen in multiple cells in the same column, but only perform that macro on the row that the drop down was changed... is that clear?
Use Target address to perform the macro on the selected cell.
I want to create a macro to provide full details from other sheet based on selected name from a drill down cell
I.e. if I have 10 staff visiting around 100 companies per day and I want to select one staff then the full details of his visit came including date of visit, name of the company etc.
Thanks in advance
The macro's worked great from the drop down list. I wanted to hide certain rows for ease of use on a form. I tried adding a second drop down and vba change coding, but without success. I am new to vba, so perhaps did it incorrectly. So,instead of the second drop down list, I added a filter to the form, but when the filter is used, the lines hidden by the original macro unhide.
Is there a way to either run two different macro combinations from two different drop lists, or alternately use the filter feature in conjunction with one macro/drop down?
Thanks.
un codigo para invertir las casilla sseleccionas con las no seleccionadas se podra?
gracias
godofredo
a code to reverse the select box with unselected could?
Thank you (Google Translate)
The following code toggles checkboxes on a worksheet:
This was really simple and worked perfectly. I used "Yes" and "No" on the dropdown to run different macros. Many thanks.
Oscar, this works pretty well. I have added a "Select one option" that appears on top of the other ones; however, if you select an option and run the corresponding macro, the list shows the last option you selected, not the first one. What should I do to always show the first option (in my case "Select an option") even after selecting an option?
Bruno
This event code shows always the first option.
Thanks Oscar! It works perfectly.
Hi,
I am trying to use this code for various dropdown boxes on the same worksheet.
Background:
I am working KPI's for several departments that I would firstly like to filter by department name (this is what I used the above code for). Secondly, I would like another dropdown box in a different cell that enables the user to filter by month. However, I cannot seem to get this to work. The dropdown opens but does not run the macros.
Any help would be appreciated.
Many thanks,
Lee Wood
Have you tried the excel file attached to this post?
It might give a clue what is wrong with you workbook.
Make sure you spell the macro name correctly in your vba code
Macro names used in above code:
Macro1
Macro2
I presume your macros work if you run them?
Are the macros in the same workbook?
Did you put your code in a code module?
Hello Oscar,
I am running your code, exact same position exact same scripts, but once I change from dropdown list from Macro1 to Macro2 I get the next error: "Compile Error: Sub or Function not defined" .
Also what is the script once I chose the item from dropdown list to automaticly change a cell into what I want?
Thank you for everything Oscar.
I have just opened your xsl. file, and it works on your file, why doesn't work on mine? I use exact same position exact same script.
Does it have anything to do with the fact that I am on my third sheet?
Cristi
I am running your code, exact same position exact same scripts, but once I change from dropdown list from Macro1 to Macro2 I get the next error: "Compile Error: Sub or Function not defined" .
Does it have anything to do with the fact that I am on my third sheet?
Yes, make sure you have your event code on your third sheet. See blog post instructions below "Create a change event".
Dear Sir,
I tried your macro, it works perfect until reach the data validation source character limitation. Do you have any suggestion for limitless source macro source
Thanks in advance
Hi there,
First of all thx for the post. I find it very usefull! I works fine in my case. However, when I extend the range to various cells (all of them with the same drop down list), a "Run-time error ‘13’: Type mismatch" pops up from the VBA editor.
Any suggestion on how to solve it?
Thx in advance!!
German
German
Which line in the VBA code is highlighted when this error shows up?
Perhaps this explains why:
https://excelmacromastery.com/vba-type-mismatch/
When I use this with a Number List - Each time I select 0 I can't use the drop down menu. It keeps running the same Macro over and over. I can't even select the cell to change it.
When I comment out your code - I can do anything.
Try making sure that you've specified "worksheet" and "change" in your Sheet1 Code dropdowns. I had the same problem, and it was because I had "sheet change" on the right dropdown instead of "change"
Well Explained.Immensely benefited.Thanks a lot Oscar
I have 2 Dropdown List with the same options (Included and Excluded) in different sheets. If I select " Included" in one dropdown list, it should also select "Included" on another dropdown list and vice versa. I need VBA coding for this to execute
Hi! I tried the Macro, and it worked when I used Macro 1/ Macro 2.
I tried to implement it for my codes though, and it did not work. The event is in Sheets, the Macros in Modules. But I change the values of the dropdown list and it does not work. Have I done something wrong in the code?
Private Sub Wywolanie(ByVal Target As Range) 'do przebadania/ miasta powinno tu być
If Not Intersect(Target, Range("H15")) Is Nothing Then
Select Case Range("H15")
Case "Bialystok": Call Raporty_Miast
Case "Katowice": Call Raporty_Miast
Case "Kilece": Raporty_Miast
Case "Koszalin": Raporty_Miast
Case "Krakow": Raporty_Miast
Case "Lodz": Raporty_Miast
Case "Lublin": Raporty_Miast
Case "Opole": Raporty_Miast
Case "Poznan": Raporty_Miast
Case "Rzeszow": Raporty_Miast
Case "Sopot": Raporty_Miast
Case "Warszawa": Raporty_Miast
Case "Wroclaw": Raporty_Miast
Case "Zielona Gora": Raporty_Miast
End Select
End If
End Sub
I would appreciate any help! Thank you!
Okay, I found out,
the name of the macro has to be exactly
Private Sub Worksheet_Change(ByVal Target As Range)
this worked