Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 More…Less
You can use a Form control button or a command button (an ActiveX control) to run a macro that performs an action when a user clicks it. Both these buttons are also known as a push button, which can be set up to automate the printing of a worksheet, filtering data, or calculating numbers. In general, a Form control button and an ActiveX control command button are similar in appearance and function. However, they do have a few differences, which are explained in the following sections.
Button (Form control)
|
Command button (ActiveX control)
|
In the sections below, learn how to add a macro to a button in Excel—for Windows or the Mac.
Note: ActiveX controls are not supported on the Mac.
Macros and VBA tools can be found on the Developer tab, which is hidden by default.
The first step is to enable it. For more information, see the article: Show the Developer tab.
Add a button (Form control)
-
On the Developer tab, in the Controls group, click Insert, and then under Form Controls, click Button .
-
Click the worksheet location where you want the upper-left corner of the button to appear. The Assign Macro popup window appears.
-
Assign a macro to the button, and then click OK.
-
To specify the control properties of the button, right-click the button, and then click Format Control.
Add a command button (ActiveX control)
-
On the Developer tab, in the Controls group, click Insert, and then under ActiveX Controls, click Command Button .
-
Click the worksheet location at which you want the upper-left corner of the command button to appear.
-
In the Controls group, click View Code. This launches the Visual Basic Editor. Ensure that Click is chose in the drop-down list on the right. The sub procedure CommandButton1_Click (see the figure below) runs these two macros when the button is clicked: SelectC15 and HelloMessage.
-
In the subprocedure for the command button, do either of the following:
-
Enter the name of an existing macro in the workbook. You can find macros by clicking Macros in the Code group. You can run multiple macros from a button by entering the macro names on separate lines inside the subprocedure.
-
As necessary, add your own VBA code.
-
-
Close the Visual Basic Editor, and click Design Mode to ensure design mode is off.
-
To run the VBA code that is now part of the button, click the ActiveX command button that you just created.
-
To edit the ActiveX control, make sure that you are in design mode. On the Developer tab, in the Controls group, turn on Design Mode.
-
To specify the control properties of the command button, on the Developer tab, in the Controls group, click Properties . You can also right-click the command button, and then click Properties.
Note: Before you click Properties, make sure that the object for which you want to examine or change properties is already selected.
The Properties box appears. For detailed information about each property, select the property, and then press F1 to display a Visual Basic Help topic. You can also type the property name in the Visual Basic Help Search box. The following table summarizes the properties that are available.
If you want to specify |
Use this property |
---|---|
General: |
|
Whether the control is loaded when the workbook is opened. (Ignored for ActiveX controls.) |
AutoLoad (Excel) |
Whether the control can receive focus and respond to user-generated events. |
Enabled (Form) |
Whether the control can be edited. |
Locked (Form) |
The name of the control. |
Name (Form) |
The way the control is attached to the cells below it (free floating, move but do not size, or move and size). |
Placement (Excel) |
Whether the control can be printed. |
PrintObject (Excel) |
Whether the control is visible or hidden. |
Visible (Form) |
Text: |
|
Font attributes (bold, italic, size, strikethrough, underline, and weight). |
Bold, Italic, Size, StrikeThrough, Underline, Weight (Form) |
Descriptive text on the control that identifies or describes it. |
Caption (Form) |
Whether the contents of the control automatically wrap at the end of a line. |
WordWrap (Form) |
Size and Position: |
|
Whether the size of the control automatically adjusts to display all the contents. |
AutoSize (Form) |
The height or width in points. |
Height, Width (Form) |
The distance between the control and the left or top edge of the worksheet. |
Left, Top (Form) |
Formatting: |
|
The background color. |
BackColor (Form) |
The background style (transparent or opaque). |
BackStyle (Form) |
The foreground color. |
ForeColor (Form) |
Whether the control has a shadow. |
Shadow (Excel) |
Image: |
|
The bitmap to display in the control. |
Picture (Form) |
The location of the picture relative to its caption (left, top, right, and so on). |
PicturePosition (Form) |
Keyboard and Mouse: |
|
The shortcut key for the control. |
Accelerator (Form) |
A custom mouse icon. |
MouseIcon (Form) |
The type of pointer that is displayed when the user positions the mouse over a particular object (standard, arrow, I-beam, and so on). |
MousePointer (Form) |
Whether the control takes the focus when clicked. |
TakeFocusOnClick (Form) |
Macros and VBA tools can be found on the Developer tab, which is hidden by default, so the first step is to enable it
-
Go to Excel > Preferences… > Ribbon & Toolbar.
-
In the Customize the Ribbon category, in the Main Tabs list, select the Developer check box, and then click Save.
Add a button (Form control)
Follow these steps:
-
On the Developer tab, click Button .
-
Click the worksheet location where you want the upper-left corner of the button to appear. The Assign Macro popup window appears.
Note: If you have already inserted a button, you can right-click on it, and select Assign Macro.
-
Assign a macro to the button and click OK.
-
To specify the control properties of the button, right-click it, and then select Format Control….
Add a command button (Visual Basic control)
-
On the Developer tab, click Button .
-
Click the worksheet location where you want the upper-left corner of the command button to appear.
Note: If you have already inserted a button, you can right-click on it, and select Assign Macro.
-
In the Assign Macro dialog box, select New, which will open the Visual Basic Editor (VBE) to a pane with the following code:
Sub ButtonX_Click() End Sub
-
In the subprocedure for the command button, between the Sub and End Sub lines, do either of the following:
-
Enter the name of an existing macro in the workbook. You can run multiple macros from a button by typing the macro names on separate lines inside the sub procedure
-
Add your own VBA code.
-
-
Click Design Mode to ensure that design mode is off, then close the Visual Basic Editor window.
-
To edit the button, right-click it and choose Visual Basic.
-
To specify the control properties of the button, right-click it, and then select Format Control….
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
See Also
-
Add or edit a macro for a control on a worksheet
-
Enable or disable macros in Office files
-
Enable or disable ActiveX settings in Office files
Need more help?
Вставка командной кнопки на рабочий лист для начинающих программировать с нуля. Кнопки из коллекций «Элементы управления формы» и «Элементы ActiveX».
Начинаем программировать с нуля
Часть 3. Первая кнопка
[Часть 1] [Часть 2] [Часть 3] [Часть 4]
Добавление вкладки «Разработчик»
Вкладка с инструментами, связанными с VBA Excel, называется «Разработчик». Если этой вкладки нет на вашей ленте, добавьте ее через окно «Параметры»:
Порядок действий:
- Откройте окно «Параметры» через меню «Файл».
- Выберите вкладку «Настроить ленту».
- В правой колонке установите галочку у пункта «Разработчик» и нажмите «OK».
Кнопка – элемент управления формы
Вставка кнопки на лист
- Выберите вкладку «Разработчик» и нажмите на кнопку «Вставить».
- Нажмите на значок кнопки в коллекции «Элементы управления формы».
- Кликните в любом месте на рабочем листе Excel.
- Откроется окно «Назначить макрос объекту». Нажмите «Отмена», так как макрос для этой кнопки еще не готов.
- После нажатия кнопки «Отмена», на рабочем листе появится новая кнопка из коллекции «Элементы управления формы» в режиме редактирования.
Ухватив мышкой за один из кружочков, можно изменить размер кнопки. Ухватив кнопку за границу, можно перетащить ее в другое место. Также, в режиме редактирования, можно изменить название кнопки прямо на ее поверхности.
Чтобы выйти из режима редактирования кнопки из коллекции «Элементы управления формы», кликните в любом месте на рабочем листе.
Чтобы вернуться в режим редактирования кнопки, кликните по ней правой кнопкой мыши и выберите из контекстного меню нужный пункт. Если вы хотите изменить размер или размещение кнопки перетаскиванием, кликните левой кнопкой мыши в любом месте рабочего листа. После первого клика контекстное меню закроется, а кнопка останется в режиме редактирования.
Создание процедуры для кнопки
Кнопке из коллекции «Элементы управления формы» можно назначить макрос (процедуру), размещенную в стандартном программном модуле.
Создайте или откройте файл Excel с расширением .xlsm (Книга Excel с поддержкой макросов) и перейдите в редактор VBA, нажав сочетание клавиш «Левая_клавиша_Alt+F11».
Если вы не создавали ранее в этом проекте VBA стандартный программный модуль, нажмите кнопку «Module» во вкладке «Insert» главного меню. То же подменю откроется при нажатии на вторую кнопку (после значка Excel) на панели инструментов.
Ссылка на модуль появится в проводнике слева. Если модуль создан ранее, дважды кликните по его ссылке в проводнике, и он откроется справа для редактирования.
Нажмите кнопку «Procedure…» во вкладке «Insert» главного меню. Та же ссылка будет доступна при нажатии на вторую кнопку после значка Excel на панели инструментов.
В открывшемся окне добавления шаблона процедуры оставьте выбранным переключатель «Sub», вставьте в поле «Name» название процедуры «NovayaProtsedura» и нажмите «OK».
В стандартный программный модуль будет вставлен шаблон процедуры «NovayaProtsedura».
Вставьте внутрь шаблона процедуры следующий код:
‘Записываем в ячейку A1 число 44 Cells(1, 1) = 44 ‘Записываем в ячейку B1 число 56 Cells(1, 2) = 56 ‘Записываем в ячейку C1 формулу, которая ‘вычисляет сумму значений ячеек A1 и B1 Cells(1, 3) = «=A1+B1» |
На этом процедура (подпрограмма, макрос) для кнопки готова.
Назначение макроса кнопке
Кликните правой кнопкой мыши по кнопке на рабочем листе и в контекстном меню выберите строку «Назначить макрос…», откроется окно «Назначить макрос объекту».
Выберите в списке процедуру «NovayaProtsedura» и нажмите «OK». Кликните левой кнопкой мыши по рабочему листу, чтобы командная кнопка вышла из режима редактирования.
Теперь можете нажать созданную кнопку из коллекции «Элементы управления формы» для проверки ее работоспособности.
Кнопка – элемент ActiveX
Вставка кнопки на лист
- Выберите вкладку «Разработчик» и нажмите на кнопку «Вставить».
- Нажмите на значок кнопки в коллекции «Элементы ActiveX».
- Кликните по рабочему листу и кнопка из коллекции «Элементы ActiveX» появится рядом с курсором.
- Автоматически включится режим редактирования, включение и отключение которого осуществляется кнопкой «Режим конструктора».
Ухватив кнопку за кружок, можно изменить ее размер, а ухватив за границу – перетащить на другое место. Чтобы отредактировать наименование кнопки, нужно кликнуть на ней правой кнопкой мыши и в контекстном меню выбрать «Объект CommandButton» > «Edit».
Добавление процедуры
Кликните дважды по кнопке из коллекции «Элементы ActiveX» левой кнопкой мыши в режиме конструктора. Это приведет к открытию модуля листа, на который вставлена кнопка, и записи шаблона процедуры «CommandButton1_Click».
Вставьте внутрь шаблона процедуры код, который будет очищать ячейки A1, B1 и C1:
Перейдите на рабочий лист и, если кнопка «Режим конструктора» затемнена, нажмите на нее, чтобы выйти из режима редактирования. После этого нажмите кнопку «CommandButton1», и она очистит ячейки, заполненные ранее нажатием кнопки «Кнопка 1».
Теперь кнопка из коллекции «Элементы управления формы» (Кнопка 1) будет заполнять ячейки диапазона «A1:C1», а кнопка из коллекции «Элементы ActiveX» (CommandButton1) очищать их.
In this Article
- Adding a Macro Button to an Excel Worksheet
- Adding a Form Control Button
- Adding an ActiveX Button
- Adding a Macro to a Shape in an Excel Worksheet
- Adding Command Buttons to VBA Forms
This tutorial will demonstrate how to add a macro button in Excel VBA.
Once we have created macros in Excel, it is sometimes useful to create a button in the Excel worksheet to run the macro.
Also, as we use VBA to create UserForms in Excel, we need to be able to create buttons on these UserForms to perform the OK and Cancel operations. This tutorial will demonstrate how to add a macro button to a VBA worksheet, how to add a macro to a shape in VBA (as opposed to a button), and how to add a button onto a User Form in the VBE Editor.
Adding a Macro Button to an Excel Worksheet
Once we have created a macro in Excel VBA, we can create a button on the worksheet to run the macro.
In the Ribbon, select the Developer tab if it is visible. This tab is switched off by default so you will need to switch it on to see the tab on the ribbon.
If the Developer tab is not visible on the ribbon, click on the File tab in the Ribbon, and go down to Options. In the Customize Ribbon options, tick the Developer check box.
Click OK.
The Developer tab will appear on the main ribbon.
There are 2 types of buttons we can add to an Excel sheet – a Form Control button and an ActiveX Control Button.
Adding a Form Control Button
In the Ribbon, select Developer > Insert > Form Controls > Button.
Click and drag in the worksheet to create a button. As soon as you release the mouse button, the assign macro dialog box will appear.
Scroll down to 1) select the macro you wish to assign to the button, and then, 2) click OK.
Right click on the button, and select Edit Text to change the text on the button.
Type an appropriate name for the button and then click off the button.
Click the button to run the macro.
To change the format of the button, right click on the button and select Format Control.
Select the options to format, and click OK.
Adding an ActiveX Button
The ActiveX button is similar to a Form Control Button but instead of assigning an existing macro to the button, we need to write code behind the Click Event of the button. It also has a lot more Properties than the Form Control Button making it a much more flexible control.
In the Ribbon, select Developer > Insert > ActiveX Controls > Command button.
Click and drag in your worksheet to create the button. The button will appear as an Embedded Command Button.
To change the name of the command button, or the text that is displayed, right-click on the command button and click on Properties.
Amend the 1) name of the button, 2) caption of the button and 3) format of the text as required.
To add code to the button, right-click on the button once more and select View Code.
This will automatically create the click event for the button in the VBE Editor. (the click event is the most common event for command buttons and is created by default).
Type the code you require into the event that has been created.
Private Sub cmdTime_Click()
Dim strT As String
strT = Time()
MsgBox "The time right now is " & strT
End Sub
Close the VBE Editor to return to your worksheet.
Click once more on your new button. You will notice that macro does not run, but the button gets selected. This is due to the fact that when you create an ActiveX button, you are automatically put into Design Mode.
To run the code behind the button, click on the Design Mode button on the Ribbon to go out of Design mode, and then click the button.
Adding a Macro to a Shape in an Excel Worksheet
In the Ribbon, select Insert > Shape.
Select the shape from the drop down, and then drag in the Excel worksheet to create the shape.
Right-click on the shape, and select Assign Macro.
Select the macro to assign, and then click OK.
When you move your mouse over your shape, the mouse cursor should turn into a small hand. Click on the shape to run the macro.
Adding Command Buttons to VBA Forms
Creating VBA UserForms is a big part of programming in VBA. It allows you to build a professional looking user interface to communicate with the users of your VBA application. It also allows you to totally control the user in what they are doing to your workbook. To learn how to create UserForms in VBA, click here.
Once a UserForm is created, and controls have been added to a UserForm, buttons can be added to perform functions such as OK and Cancel.
In the Toolbox, select the Command Button control, and then click and drag in your form to create the button.
Using the Caption Property, change the caption of the command button to OK, and the Accelerator to “O”
The purpose of the Accelerator is for the user to use the keyboard to activate the button, in this case Alt+O would activate the button.
Once we have created the command button, we can double-click on the command button to go to the VBA code. Double-clicking on the command button in the form will automatically create the Click Event for the button as this is the event that is most commonly used by command buttons.
We can now type our relevant VBA code within the procedure that has been created.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Bottom Line: Learn how to create macro buttons in a worksheet that run VBA code when clicked. Includes how to format buttons and prevent them from moving and resizing on the sheet.
Skill Level: Intermediate
Video Tutorial
Download the Excel File
Here’s the Excel workbook that I use in the video so you can follow along and practice what you’re learning.
Making User-Friendly Macro Buttons in Your Spreadsheets
Macros make life easier. Buttons make life easier. It’s only natural to marry the two and make the processes you repeatedly have to perform as simple as possible.
You can literally run through a hundred steps with just one small click using macros and buttons–which, of course, is both empowering and gratifying.
Kristen, a member of our VBA Pro Course, loves to add buttons to her spreadsheets for this reason.
You can watch the entire video to learn more about Kristen’s story with learning VBA, and how she uses macro buttons.
For this tutorial, we’re using macros that have already been created. If you don’t know how to create macros yet, then checkout one of my free webinars to learn the basics getting started with macros & VBA.
So let’s take a look at how to create a button and assign a macro to it.
3 Types of Macro Buttons for Worksheets
In this post I explain three different types of buttons you can place on a worksheet.
- Shapes
- Form Control Buttons
- ActiveX Control Buttons
We’ll start with my favorite…
1. Using Shapes to Create Macro Buttons
In my opinion, the best way to create macro buttons is to use shapes. Shapes give us the most styling/formatting options, and we can make them look like buttons you click every day on modern web pages.
Below, we will create the button on a worksheet and assign a macro to it. Here are the steps to create the macro button:
1. Draw a shape on the sheet (Insert tab > Shapes drop-down > Rectangle shape).
2. Add text to the shape (Right-click > Edit Text | or double-click in the shape).
3. Assign the macro (Right-click the border of the shape > Assign Macro…)
4. Select the macro from the list. It’s important to note that the macro should be selected from the This Workbook list so that when you share the workbook with other users, the macro will be shared as well.
If you assign the macro from another workbook, the button will not work for the people you share the workbook with.
5. Press OK.
When you hover your mouse over the shape it will now turn into the hand pointer cursor. Clicking the shape will run the macro.
That’s it! That’s how you assign a macro to a button that you’ve created right on the worksheet.
Modifying the Button
If you need to select the shape to change its look or move it, hold the Ctrl key while clicking the shape. This will prevent the macro from running and allow you to modify the shape. Excel offers a ton of options on the Format tab for changing the shape style, shape effects, font color or size, etc.
Preventing the Button from Resizing with Cell Changes
Depending on your settings, it’s likely that when you change the size of the column or row that your button is on, the button size will change as well. If you don’t want that to happen, you can easily adjust the settings to keep the button static.
First, just right click on the button and choose Size and Properties…
This will bring up the Format Shape pane. There are options for you to choose from in the Properties section, depending on whether or not you want the button to move or resize when changes are made to your sheet.
2. Using Form Controls to Create Macro Buttons
The next option for macro buttons is Form Controls. They are essentially the same in terms of set-up.
The difference between Controls and Shapes is the styling.
Form Control buttons do give the appearance of being pressed when you click on them, which is kind of cool. However, they unfortunately look like a button you’d find on an early version of Windows.
We cannot change the color of the button either. The only formatting options are for the font type, size, and color.
Insert a Form Control Button
To add a Form Control button, just go to the Developer tab and click on the Insert button. A drop-down gives you options under Form Controls.
3. Using ActiveX Controls for Macro Buttons
The last option is ActiveX Control buttons.
The ActiveX Control buttons do have more formatting options and you can change the button color.
They also require you to add an event macro in the sheet module that will run when the button is clicked. This is done by right-clicking the button and choosing View Code.
You can add other event triggers like double-click. This could perform a different action/macro when the button is double-clicked.
However, I don’t recommend the ActiveX Control buttons. In my experience they are glitchy in terms of consistent appearance. They can end up really big or really small when changes are made to the sheet or when the file is shared back and forth between users.
Placing Buttons in the Ribbon or Toolbar Instead
Another option is to place your macro buttons on any of the tabs in the Excel Ribbon or Quick Access Toolbar.
This is video #3 in my 4-part video series on the Personal Macro Workbook. This technique is best for macros that you will only run on your computer because the ribbon button customizations do not travel with the workbook.
If you do want the ribbon buttons to travel with the workbook then you can use XML code to customize the ribbon. I’ll write an article on that in the future, and I do cover extensively in my VBA Pro Course, along with how to create add-ins.
Related Tutorials
I have a couple other posts for you to check out on this topic. Take a few minutes to give them a look!
- How to Create VBA Macro Buttons for Filters in Excel
- Macro Buttons to Add Fields to Pivot Tables
- How to Add a Yes No Pop-up Message Box to a Macro Before It Runs
- How to Enable the Developer Tab in Excel
Conclusion
My overall recommendation is to keep it simple and stick to using shapes for macro buttons. They give you the most formatting options, and are easy to setup and modify.
What will you create macro buttons for? I’d love to hear how you plan to put these buttons to work. If you have any comments or questions about running a macro button that you’ve created, please leave a comment below.
Thank you! 🙂
One of the coolest things about Excel is the ability to add Form Controls. Form Controls are interactive UI elements you have probably seen many times. They can be:
- Command Buttons
- Combo boxes
- Checkboxes
Form Controls are great because they are intuitive ways to interact with a piece of software that everyone can understand. Implementing them in an Excel sheet can really open up the complexity options in your project.
But, how do you use them? Form Controls can bring a lot to your application, but they are a little more complicated to configure and use in VBA. In this blog post, I am going to go through each Form Control and explain how to configure it, interact with it, and use it in a piece of code.
Let’s get started!
Adding Form Controls To A Spreadsheet
To add Form Controls to a spreadsheet, you will need to enable the Developer section of the toolbar:
If you do not see this tab on your toolbar, navigate to File –> Options:
And go to the ‘Customize Ribbon’ section:
Add the Developer option to your Main Tabs and click ‘OK.’ You should then be set to add Form Controls.
Command Button Form Controls
The first option you have for Form Controls is the command button. This is one of the most basic controls found in any application.
It is simply a button that you click on to trigger some other action. You can also format the label on the button and give it a few different colors and sizes. To add a command button to a sheet, go to your ‘Developer’ tab and under ‘Insert,’ select the first option:
Once selected, your cursor will change into a crosshair. You can now click and drag a rectangle onto your sheet, and the rectangle will be the size of your button:
When you let go of your mouse, Excel will automatically open a window that will ask you if you want to link a macro to this button:
In this case, thus button was the 8th Form Control I added to this sheet, so it shows up automatically as ‘Button8.’ When you go further into the macro by clicking ‘New,’ you will see the following:
Sub Button8_Click()
End Sub
With this, you can now create an event for your button to trigger when its clicked. Let’s create a button that puts a hard-coded value into a cell:
Sub Button8_Click()
ActiveSheet.Cells(1, 1).Value = "Button was clicked!"
End Sub
Pretty easy right!? You can change the macro that gets fired off of this button by right-clicking on it and selecting ‘Assign Macro,’ and then choose the macro you want.
Command Button in VBA
Having a button and a macro are great, but what if you wanted to access your button in a macro? Well, paste the following code below and you can paste the button text in a cell:
Sub Button8_Click()
ActiveSheet.Cells(1, 1).Value = ActiveSheet.Shapes("Button 8").OLEFormat.Object.Caption
End Sub
It’s important to note that there is a space between ‘Button’ and ‘8’ in the above macro. To access Form Controls on your sheet in VBA, you need to use the syntax:
Activesheet.Shapes([Optional Object Name]).OLEFormat.Object
The above syntax will then let you access a Form Controls properties and methods. For the command button, its properties and methods are listed here.
In this example, I am using the ‘Caption’ property to get the text on the button and paste it in a cell:
Ta-da! You can build some really advanced logic on your spreadsheets with controls once you can access them in VBA.
Combo Box Form Controls
The combo box, also known as a drop-down list, is a box with an arrow that shows you options when clicked. Clicking one of the options select it as the controls value:
To add a combo box to your spreadsheet, click on the ‘Insert’ option under the ‘Developer’ ribbon and select the second option:
Now, when you select this option, your cursor will, again, turn into a crosshair. Draw the size of the rectangle you want the combo box to be and it will render on the page.
You’ll notice you are not prompted to assign the combo box to a macro once it’s rendered. Normally, the combo box is not designed to trigger a macro, but it can be. Before we get to that, let’s configure our combo box. Right-click on it and select ‘Format Control’ and navigate to the ‘Control’ tab:
The tabs before control allow allow you to configure the visuals of the combo box, but the Control tab is where you can configure its values and what cell you can see the selected value index in.
In some other cells on the sheet, type in the values you want in the combo box, each in a separate cell, and link them to your input:
Select a single cell for the ‘Cell link’ option, and that cell will get the index of the combo box value selected, and it will update every time to combo box is updated:
Now, try out your combo box!
Pretty cool! You can also assign a macro to a combo box in the same way you can to a Command Button, and it will fire every time the value of the combo box is updated.
Combo Box In VBA
Having a combo box is great and being able to assign a macro to it is also helpful. But what if you wanted to put some more complex logic in the macro? Say you only wanted the macro to do something when a certain combo box value was selected. To get the value of a combo box in VBA:
Sub DropDown11_Change()
Dim index As Long
index = ActiveSheet.Shapes("Drop Down 11").OLEFormat.Object.ListIndex
If index = 2 Then
ActiveSheet.Cells(1, 4).Value = ActiveSheet.Shapes("Drop Down 11").OLEFormat.Object.List(index)
Else
ActiveSheet.Cells(1, 4).Value = ""
End If
End Sub
The above code will get the index of the combo box value when it changes. If that index is 2, we write the value of the list item in our cell. If not, it clears the cell out:
When we select the second option:
And picking something else again:
As you can see, you can do a lot with VBA and Form Controls once you get the hang of it. The other methods and properties available for a combo box can be seen here.
Checkbox Form Controls
Everyone has used a checkbox when interacting with a web app. A checkbox give users a simple way to specify a ‘True’ or ‘False’ value:
To insert a check box on an Excel sheet, select the ‘Insert’ option under the ‘Developer’ tab and select the third option:
When you select it, your cursor will turn into a crosshair. Click on the sheet where you want your checkbox to render and it will appear:
For a checkbox, the most important configuration option is the ‘Cell link.’ You can specify a cell to hold the value of the checkbox as it changes:
Specify the cell you want to hold the checkbox value and:
Pretty cool! You can also assign a macro to checkbox and it will fire upon change.
Checkbox In VBA
A checkbox is very handy, but in a macro, the most important part of it is getting the checkbox value. Say you wanted to fire a macro and check that checkbox value to build some interesting logic:
Sub CheckBox12_Click()
Dim checkboxvalue As Integer
checkboxvalue = ActiveSheet.Shapes("Check Box 12").OLEFormat.Object.Value
Debug.Print (checkboxvalue)
End Sub
If you run this macro, you can see in the VBA window that a value of True = 1 and a value of False = -4146. Why? I’m not sure, but you can use it for whatever logic you need!
You can see other properties and methods of the checkbox Form Control here.
Iterating Over Multiple Form Controls
Once you start using Form Controls in VBA, you can use the Shapes() method to get all the controls on a page and start iterating over them to see what;s on your sheet and how you can get their properties:
Sub ShapeNames()
For Each obj In ActiveSheet.Shapes()
Debug.Print (obj.OLEFormat.Object.Name)
Next
End Sub
Running the above code for my sheet, I get:
The above code can be very helpful in figuring out what’s on your sheet and how you can reference it. Try combining From Controls with some of the other VBA code to make a dynamic, living application. Happy macro’ing!