Visual basic button excel

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)

Example of a Forms toolbar button control

Command button (ActiveX control)

Example of an ActiveX command button 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.

Developer tab on the ribbon

Add a button (Form control)

  1. On the Developer tab, in the Controls group, click Insert, and then under Form Controls, click Button Button image .

  2. Click the worksheet location where you want the upper-left corner of the button to appear. The Assign Macro popup window appears.

  3. Assign a macro to the button, and then click OK.

  4. To specify the control properties of the button, right-click the button, and then click Format Control.

Add a command button (ActiveX control)

  1. On the Developer tab, in the Controls group, click Insert, and then under ActiveX Controls, click Command Button Button image .

  2. Click the worksheet location at which you want the upper-left corner of the command button to appear.

  3. 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.

    A subprocedure in the Visual Basic Editor

  4. 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.

  5. Close the Visual Basic Editor, and click Design Mode Button image to ensure design mode is off.

  6. To run the VBA code that is now part of the button, click the ActiveX command button that you just created.

  7. 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.

  8. To specify the control properties of the command button, on the Developer tab, in the Controls group, click Properties Button image . 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

  1. Go to Excel > Preferences… > Ribbon & Toolbar.

  2. In the Customize the Ribbon category, in the Main Tabs list, select the Developer check box, and then click Save.

    Select the checkbox next to Developer to add it to the ribbon

Add a button (Form control)

Follow these steps:

  1. On the Developer tab, click Button Button image .

  2. 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.

  3. Assign a macro to the button and click OK.

  4. To specify the control properties of the button, right-click it, and then select Format Control….
     

Add a command button (Visual Basic control)

  1. On the Developer tab, click Button Button image .

  2. 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.

  3. 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

  4. 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.

  5. Click Design Mode Button image to ensure that design mode is off, then close the Visual Basic Editor window.

  6. To edit the button, right-click it and choose Visual Basic.

  7. 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?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Вставка командной кнопки на рабочий лист для начинающих программировать с нуля. Кнопки из коллекций «Элементы управления формы» и «Элементы ActiveX».

Начинаем программировать с нуля
Часть 3. Первая кнопка
[Часть 1] [Часть 2] [Часть 3] [Часть 4]

Добавление вкладки «Разработчик»

Вкладка с инструментами, связанными с VBA Excel, называется «Разработчик». Если этой вкладки нет на вашей ленте, добавьте ее через окно «Параметры»:

Окно «Параметры Excel»

Порядок действий:

  • Откройте окно «Параметры» через меню «Файл».
  • Выберите вкладку «Настроить ленту».
  • В правой колонке установите галочку у пункта «Разработчик» и нажмите «OK».

Кнопка – элемент управления формы

Вставка кнопки на лист

  1. Выберите вкладку «Разработчик» и нажмите на кнопку «Вставить».
  2. Нажмите на значок кнопки в коллекции «Элементы управления формы».

Добавление кнопки на рабочий лист (элемент управления формы)

  1. Кликните в любом месте на рабочем листе Excel.
  2. Откроется окно «Назначить макрос объекту». Нажмите «Отмена», так как макрос для этой кнопки еще не готов.
  3. После нажатия кнопки «Отмена», на рабочем листе появится новая кнопка из коллекции «Элементы управления формы» в режиме редактирования.

Кнопка (элемент управления формы)

Ухватив мышкой за один из кружочков, можно изменить размер кнопки. Ухватив кнопку за границу, можно перетащить ее в другое место. Также, в режиме редактирования, можно изменить название кнопки прямо на ее поверхности.

Чтобы выйти из режима редактирования кнопки из коллекции «Элементы управления формы», кликните в любом месте на рабочем листе.

Чтобы вернуться в режим редактирования кнопки, кликните по ней правой кнопкой мыши и выберите из контекстного меню нужный пункт. Если вы хотите изменить размер или размещение кнопки перетаскиванием, кликните левой кнопкой мыши в любом месте рабочего листа. После первого клика контекстное меню закроется, а кнопка останется в режиме редактирования.

Создание процедуры для кнопки

Кнопке из коллекции «Элементы управления формы» можно назначить макрос (процедуру), размещенную в стандартном программном модуле.

Создайте или откройте файл Excel с расширением .xlsm (Книга Excel с поддержкой макросов) и перейдите в редактор VBA, нажав сочетание клавиш «Левая_клавиша_Alt+F11».

Если вы не создавали ранее в этом проекте VBA стандартный программный модуль, нажмите кнопку «Module» во вкладке «Insert» главного меню. То же подменю откроется при нажатии на вторую кнопку (после значка Excel) на панели инструментов.

Вставка модуля в редакторе VBA Excel

Ссылка на модуль появится в проводнике слева. Если модуль создан ранее, дважды кликните по его ссылке в проводнике, и он откроется справа для редактирования.

Нажмите кнопку «Procedure…» во вкладке «Insert» главного меню. Та же ссылка будет доступна при нажатии на вторую кнопку после значка Excel на панели инструментов.

Вставка процедуры в редакторе VBA Excel

В открывшемся окне добавления шаблона процедуры оставьте выбранным переключатель «Sub», вставьте в поле «Name» название процедуры «NovayaProtsedura» и нажмите «OK».

Окно добавления процедуры в редакторе VBA Excel

В стандартный программный модуль будет вставлен шаблон процедуры «NovayaProtsedura».

Шаблон процедуры в редакторе VBA Excel

Вставьте внутрь шаблона процедуры следующий код:

‘Записываем в ячейку A1 число 44

Cells(1, 1) = 44

‘Записываем в ячейку B1 число 56

Cells(1, 2) = 56

‘Записываем в ячейку C1 формулу, которая

‘вычисляет сумму значений ячеек A1 и B1

Cells(1, 3) = «=A1+B1»

Процедура в редакторе VBA Excel

На этом процедура (подпрограмма, макрос) для кнопки готова.

Назначение макроса кнопке

Кликните правой кнопкой мыши по кнопке на рабочем листе и в контекстном меню выберите строку «Назначить макрос…», откроется окно «Назначить макрос объекту».

Окно «Назначить макрос объекту»

Выберите в списке процедуру «NovayaProtsedura» и нажмите «OK». Кликните левой кнопкой мыши по рабочему листу, чтобы командная кнопка вышла из режима редактирования.

Теперь можете нажать созданную кнопку из коллекции «Элементы управления формы» для проверки ее работоспособности.

Кнопка – элемент ActiveX

Вставка кнопки на лист

  1. Выберите вкладку «Разработчик» и нажмите на кнопку «Вставить».
  2. Нажмите на значок кнопки в коллекции «Элементы ActiveX».

Добавление кнопки на рабочий лист (элемент ActiveX)

  1. Кликните по рабочему листу и кнопка из коллекции «Элементы ActiveX» появится рядом с курсором.
  2. Автоматически включится режим редактирования, включение и отключение которого осуществляется кнопкой «Режим конструктора».

Кнопка (элемент ActiveX)

Ухватив кнопку за кружок, можно изменить ее размер, а ухватив за границу – перетащить на другое место. Чтобы отредактировать наименование кнопки, нужно кликнуть на ней правой кнопкой мыши и в контекстном меню выбрать «Объект CommandButton» > «Edit».

Добавление процедуры

Кликните дважды по кнопке из коллекции «Элементы ActiveX» левой кнопкой мыши в режиме конструктора. Это приведет к открытию модуля листа, на который вставлена кнопка, и записи шаблона процедуры «CommandButton1_Click».

Шаблон процедуры в модуле рабочего листа Excel

Вставьте внутрь шаблона процедуры код, который будет очищать ячейки A1, B1 и C1:

Процедура в модуле рабочего листа Excel

Перейдите на рабочий лист и, если кнопка «Режим конструктора» затемнена, нажмите на нее, чтобы выйти из режима редактирования. После этого нажмите кнопку «CommandButton1», и она очистит ячейки, заполненные ранее нажатием кнопки «Кнопка 1».

Две кнопки на рабочем листе Excel

Теперь кнопка из коллекции «Элементы управления формы» (Кнопка 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.

vba vbe developer

Click OK.

The Developer tab will appear on the main ribbon.

vba vbe vbescreen

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.

VBA Buttons FormControl

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.

VBA Buttons AssignMacro

Scroll down to 1) select the macro you wish to assign to the button, and then, 2) click OK.

VBA Buttons AssignMacro OK

Right click on the button, and select Edit Text to change the text on the button.

VBA Buttons Edit Text

Type an appropriate name for the button and then click off the button.

Click the button to run the macro.

VBA Buttons ClickButton

To change the format of the button, right click on the button and select Format Control.

VBA Buttons Format

Select the options to format, and click OK.

VBA_Buttons FormControl Format

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.

VBA Buttons ActiveX Button

Click and drag in your worksheet to create the button.   The button will appear as an Embedded Command Button.

VBA Buttons ActiveX EmbeddedButton

To change the name of the command button, or the text that is displayed, right-click on the command button and click on Properties.

VBA_Buttons ActiveX Properties

Amend the 1) name of the button, 2) caption of the button and 3) format of the text as required.

VBA Buttons ActiveX Change Properties

To add code to the button, right-click on the button once more and select View Code.

VBA_Buttons ActiveX 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).

VBA Buttons ActiveX Click Event

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. 

VBA Buttons ActiveX DesignView

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.

VBA Buttons ActiveX Clicked

Adding a Macro to a Shape in an Excel Worksheet

In the Ribbon, select Insert > Shape.

VBA Buttons Insert Shape

Select the shape from the drop down, and then drag in the Excel worksheet to create the shape.

VBA Buttons DragShape

Right-click on the shape, and select Assign Macro.

VBA Buttons AssignShape Macro

Select the macro to assign, and then click OK.

VBA Buttons Shape Hand

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.

VBAControls CommandButton

Using the Caption Property, change the caption of the command button to OK, and the Accelerator to “O”

VBAControls Button Properties

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.

VBAControls Button Accelerator

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.

VBA Buttons Click Event

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!
vba save as

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

Watch on YouTube & Subscribe to our Channel

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.

Kristen Macro Buttons Testimonial Video

Click here to hear Kristen’s story with learning VBA

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.

  1. Shapes
  2. Form Control Buttons
  3. 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).

Use a Shape for a Macro Button VBA Excel

2. Add text to the shape (Right-click > Edit Text | or double-click in the shape).

Draw the macro button shape and style it

3. Assign the macro (Right-click the border of the shape > Assign Macro…)

Right-click Assign Macro Excel Shape

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.

Assign Macro Window for Macro Button Shape

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.

Left Click Shape to Run Macro - Ctrl to Select Edit Shape

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…

Change size and properties of macro button

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.

Format Shape Pane with options to keep the macro button static

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.

Form Control Buttons

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.

Form Controls menu can be used to make macro buttons

3. Using ActiveX Controls for Macro Buttons

The last option is ActiveX Control buttons.

ActiveX Menu can be used to create macro 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.

Create the Personal Macro Workbook and Add Buttons to the Ribbon

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! 🙂

Add the Form Control button, ActiveX Control button, and Excel Shapes to worksheets

How to Add a VBA Button in Excel?

When using a workbook that incorporates VBA code, you can add a macro button to make it easier for other Excel users to run the code without knowing the VBA code. Excel users use such buttons to access most of the macros in the worksheet easily.

Add a VBA Button

Adding buttons to the worksheet will help expose other users to the custom functionality of your workbook. When a VBA button is clicked, it automatically activates a macro, and it eliminates the need to use the Developer tab to create or access macros.

Types of VBA Buttons for Worksheets

1. Form Control Buttons

Form control is one of the main ways of creating a button that runs a macro when a user clicks on it. It works in the same way as ActiveX control buttons, but they differ in several aspects.

Form control buttons give the impression of being pressed when a user clicks on them, and their appearance resembles buttons used in older versions of MS Windows. The buttons allow users to change the type, size, and color of the font. However, the button color cannot be changed.

Follow the following steps to create a Form Control Button:

  1. Go to the Developer tab and click Insert under the Control section.
  2. Click the Insert button in the drop-down list that opens.
  3. Position your cursor in the worksheet location where you want the button to be created.
  4. A pop-up window will appear. Click Assign Macro and confirm.
  5. Once the button is created, right-click on it, and click Form Control. It enables you to manage the button’s properties.

To change the button label, right-click on the button and select Edit Text from the drop-down list. You can also re-assign the macro by clicking the Assign Macro option from the drop-down list.

2. ActiveX Control Button

ActiveX Control buttons are the best alternative to Form Control buttons, and they allow more formatting options than the latter. When creating buttons using ActiveX, users are required to add the event macro to the sheet model. The macro will be triggered when the macro is clicked.

ActiveX Control buttons also allow users to add other event triggers, such as double-click. It lets users perform additional actions when the button is double-clicked.

Follow the below steps to create an ActiveX Control Button:

  1. Open the Developer tab and go to the Control section. Click Insert and scroll to the ActiveX controls.
  2. Click the first button below the ActiveX controls (Command button).
  3. Position your cursor on the worksheet location where you want your button to appear.
  4. To create the macro, click View Code in the Controls group under the Developer tab to launch the VBA editor. Choose CommandButton1 on the subprocedure (on the left). Press Click on the drop-down list on the right side of the VBA editor window.
  5. In the subprocedure, enter the name of an existing macro or create your own VBA code. You can find existing macros in the workbook by clicking Macros in the Code section. You can add multiple macros by entering the name of each macro on separate lines in the VBA editor.
  6. Click the Design mode to turn it off and close the VBA editor before running the VBA code. Then, create the ActiveX button create in the worksheet to run the macro.
  7. To change the button properties, click the Properties option under the Controls group section. Alternatively, right-click on the button and select Properties in the dropdown.

3. Excel Shapes

Apart from creating buttons from the Developer tab, Excel users can use Excel Shapes to create the buttons. The advantage of using Excel Shapes over Form Control buttons or ActiveX Control buttons is that shapes allow the most formatting and styling options. You can change button color, design, and font to make the buttons look modern.

Here are the steps to create a button in Excel using Excel Shapes:

  1. Click on the Insert tab and then click on Shapes.
  2. Select the preferred shape of your button (we selected a rounded rectangle).
  3. Drag and drop the selected shape to the preferred location on the worksheet to set the size of the shape.
  4. Right-click on the button and select Edit Text to change the button label. You can also format the button using the tools available under the Home tab.
  5. To specify a macro, right-click on the button and select Assign Macro.
  6. Select the macro from This Workbook list to make the macros shareable with other users who use the workbook. Press OK to confirm the macro.
  7. Click the button to trigger the macro operation.

Additional Resources

Through business intelligence and data analysis courses, training, and exercises, anyone in the world can become a great analyst. To keep advancing your career, the additional CFI resources below will be useful:

  • Excel VBA Examples
  • VBA in Excel
  • VBA Quick Reference
  • Transitioning from Excel to Python
  • See all Excel resources

Понравилась статья? Поделить с друзьями:
  • Visual basic application for excel 2013
  • Visual basic and application excel
  • Visual basic 2010 excel 2007
  • Visual basic 2010 and excel
  • Vista and microsoft word