Содержание
- Assign a macro to a Form or a Control button
- Add a button (Form control)
- Add a command button (ActiveX control)
- Add a button (Form control)
- Add a command button (Visual Basic control)
- Need more help?
- Add a Button and Assign a Macro in Excel
- Excel Buttons
- Run a Macro From a Button
- The Excel Developer Tab
- Add a Macro Button
- Assigning a Macro to a Button
- Assign Existing Macro to a Button
- Edit an Existing Macro Before Assigning to a Button
- Record a Macro and Assign to Button
- Write VBA Procedure and Assign to Button
- Change Macro Assigned to Button
- How to Adjust Button Properties in Excel
- Move or Resize Excel Button
- Rename Button
- Format Button
- Assign a Macro to a Shape
- Assign a Macro to a Hyperlink
Assign a macro to a Form or a Control button
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
Whether the control is loaded when the workbook is opened. (Ignored for ActiveX controls.)
Whether the control can receive focus and respond to user-generated events.
Whether the control can be edited.
The name of the control.
The way the control is attached to the cells below it (free floating, move but do not size, or move and size).
Whether the control can be printed.
Whether the control is visible or hidden.
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.
Whether the contents of the control automatically wrap at the end of a line.
Size and Position:
Whether the size of the control automatically adjusts to display all the contents.
The height or width in points.
Height, Width (Form)
The distance between the control and the left or top edge of the worksheet.
The background color.
The background style (transparent or opaque).
The foreground color.
Whether the control has a shadow.
The bitmap to display in the control.
The location of the picture relative to its caption (left, top, right, and so on).
Keyboard and Mouse:
The shortcut key for the control.
A custom mouse icon.
The type of pointer that is displayed when the user positions the mouse over a particular object (standard, arrow, I-beam, and so on).
Whether the control takes the focus when clicked.
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:
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.
Источник
Add a Button and Assign a Macro in Excel
Excel Buttons
In Excel, Buttons are used to call Macros. This tutorial will cover how to create Excel buttons, assign Macros to them, adjust their properties, and more.
By default, Excel macros are accessible in a list via the “Macros” button on the View ribbon.
Often though, you’ll want to provide easy access to a particular macro directly on your worksheet. This can be achieved using a Button control.
A Button control looks like a Microsoft Windows button, and runs a macro when clicked. It’s a much handier way to access your most commonly used macros, and is an easy way to expose custom functionality to other users of your workbook.
Run a Macro From a Button
To run a Macro from a button in Excel, simply click the button:
The Excel Developer Tab
Buttons are accessible via the Developer Tab.
Unfortunately, Excel hides the Developer tab by default. If you don’t see the Developer Ribbon, follow these steps:
- Click File >Options in the list on the left-hand border
- In the Options dialog select Customize Ribbon > Customize the Ribbon > Main Tabs and add a check-mark in the box for “Developer”, and click OK.
Add a Macro Button
In Excel, select the Developer tab, then click on the “Insert” dropdown in the Controls section. There are several types of controls divided into two sections, “Form Controls” and “ActiveX Controls”.
For now, just click on the Button control under “Form Controls”. Next, move the mouse anywhere over the worksheet surface, then hold left-click and drag the mouse to draw the outline of a rectangle. When you release left-click, a new dialog will appear titled “Assign Macro”.
Assigning a Macro to a Button
Here you can assign an existing Macro to the button, record a new macro, create a new macro from scratch using VBA, or click “Cancel” and return to your button later.
Assign Existing Macro to a Button
To assign an existing Macro, you simply select the macro’s name in the list, then click OK.
Edit an Existing Macro Before Assigning to a Button
To edit a macro before assigning it to the button, select the macro’s name in the list and click the “Edit” button (the “New” button text changes to “Edit”).
Record a Macro and Assign to Button
To record a new macro and assign it to the button, click “Record…”. This brings up the Record Macro dialog, where you specify a name and click “OK”. The button will be assigned that macro. Meanwhile, Excel will remain in a recording state until you click “Stop Recording” in the “Code” section of the Developer tab.
Write VBA Procedure and Assign to Button
To write a new macro for the button, type a new name for your macro in the textbox at the top of the dialog, then click “New”. Excel will bring up the VB Editor, in which you’ll see a new empty macro procedure with the name you entered. This procedure will be stored in a new module, visible in the Project window.
Change Macro Assigned to Button
To change the Macro that’s assigned to a button, simply right-click the button and select Assign Macro:
Here you can see the assigned Macro and make any desired changes.
How to Adjust Button Properties in Excel
Move or Resize Excel Button
After you’ve placed a button, you can easily move or resize it. To perform any of these actions, right-click on the button. Then you can left-click and drag the button to your desired location or resize it.
Rename Button
With the button selected, left-click on the button text to edit.
To add multiple lines, simple press the ENTER key.
Format Button
To format other button properties, Right-Click > Format Control
Here you can adjust font sizes, and many other button properties:
Of particular note is the “Properties” tab, which changes how the button behaves as surrounding rows and columns are inserted, deleted, resized, or hidden/unhidden.
- Move and size with cells: The button will move and resize when rows and columns are changed.
- Move but don’t size with cells: The button will move, but not resize.
- Don’t move or size with cells: The button will not move or resize.
- Finally, Print Object can set the object to appear on printouts. This is unchecked by default, but can be toggled on if desired.
Assign a Macro to a Shape
Besides buttons, macros can assigned to other objects like Pictures, Textboxes, and Shapes. With a Picture or Shape, you can make a button that looks any way you like. Excel includes a wide variety of customizable Shapes including polygons, arrows, banners, and more that may be better suited to your worksheet than a regular button control.
Shapes are accessed from the Insert tab:
Select the shape you want from the Shape dropdown, draw it onto your worksheet as you would a button control, then right-click it and select “Assign Macro…” from the pop-up dialog. The options are the same as assigning a macro to a button.
Assign a Macro to a Hyperlink
Macros can also be assigned to hyperlinks by using VBA Events. Events are procedures that are triggered when certain actions are performed:
- Open/Close/Save Workbook
- Activate / Deactivate Worksheet
- Cell Values Change
- Click Hyperlink
- and more.
Events require knowledge of VBA. To learn more about events, visit our VBA Tutorial.
Источник
When we mention buttons in Excel, anyone who is not a consistent user will wonder what that means. Yes, Microsoft Excel does have Macros buttons which are the most advanced level of Excel. These buttons are commands initiated by a single click. It is easy to add buttons to excel. A user can simplify and save the time that they will take to navigate between different cells looking for specific information. In short, the buttons are inserted to perform specific tasks for us. The three different types of buttons you can place in a worksheet include;
- Shapes
- Form Control Buttons
This article shows how to add a button in Excel and how to assign Macros to them. With those buttons, navigating through your spreadsheet won’t be a nightmare anymore.
Method 1: Using shapes to create Macro buttons to open a particular sheet
You can create a macros button by using shapes. You can easily create a rounded rectangle; add a hyperlink to it for your worksheet. Here is what you can do;
1. On the main menu ribbon, click on the Insert tab.
2. Go to Shapes, click the drop-down arrow, and select the Rounded Rectangle icon.
3. Draw a rounded rectangle on your worksheet.
5. Format the shape by typing text into it-Right-click on the form and select edit text. Or double-click the shape.
6. To Hyperlink the shape, right-click on it and select Hyperlink from the menu. Right-clicking will display an Insert Hyperlink dialogue box.
- Under the ‘Link to’ section, select ‘Place in This Document.
- Under the ‘Type the cell reference’ section, type in the destination cell address.
- Under the ‘Or select a place in this document box, click to choose the particular sheet name. Click the OK button when done.
When you click the rounded rectangle, it will skip to the specified cell of a specified sheet.
7. To assign the macro, right-click on the table and select Assign Macro. Under the ‘Macros in’ drop-down arrow, select ‘This Workbook’. Here, select the macro from the list of macros in This Workbook.
8. Press OK. When you point your mouse on this shape, it will turn to the hand pointer cursor, and clicking the form will run the macro. Remember to set your shape not to resize with cell changes by right-clicking on it and selecting ‘Size and Properties.’
Method 2: Using Developers Form Control Buttons to create buttons in Excel
1. On the main ribbon, click on the Developer tab.
2. Go to the Insert button and click the drop-down arrow.
3. Under Form Control, select the first option called button. Draw a button on your worksheet
4. Next, in the Assign Macro dialogue box, type or select a name for the macro.
5. Click OK when done. You can click on this button to run the macro.
Using ActiveX Controls
Since running a macro in Excel can prove tedious, you can assign a macro to a button to run it faster. In this case, you can follow these steps to add a button in Excel using ActiveX controls easily.
1. Right-click anywhere on the Home ribbon and select Customize the Ribbon option from the pop-up menu.
2. Once the Customize the Ribbon window is open, go to the Main Tabs section and select the Developer option.
3. Click OK. However, if you already have the Developer Tab added to your ribbon, then proceed as follows.
4. Go to the Developer Tab and click on Insert.
5. Next, click on your preferred button under the ActiveX Controls.
You can now drag it anywhere in the Excel worksheet to create a button.
6. Right-click on the newly created button and select the View Code option from the drop-down menu.
7. You can now type this code, which sets the value of cell A6 to Hello:
Range(“A6”).Value = “Hello”
8. If you want to test setting the cell value, ensure the Design Mode option is deselected. You can also click on the button, and the Hello text will be displayed on your screen.
You can further use VBA codes to assign a different task for various operations such as double-clicking, single-clicking, right-clicking, and many more. When you right-click on the button, you can also select the Format Control option. However, the only downside is that the size of the buttons changes every time you make changes on the worksheet or share it.
Adding Macros To Quick Access Toolbar
Adding macros to Quick Access Toolbar also allows you to create buttons in Excel and use them on any sheet in your present workbook. To do this, follow these steps:
1. Right-click on the arrow below the ribbon of the Excel workbook.
2. When the Customize Quick Access Toolbar screen opens, navigate and select More Commands at the bottom.
3. Select Macros in the Choose commands from the section. You can click on the down-facing arrow in the Popular Commands box.
4. Select the HighlightMaxValue option and click on the Add button.
5. You can now click on Modify to customize the symbol of the macro.
6. Select your preferred symbol from the provided list and hit the OK button.
7. Finish by clicking OK to add a button to your Excel workbook. If you want to run the HighlightMaxValue macro, simply click on the icon.
Conclusion
When working with adding buttons to Excel, it is best to keep it easy and straightforward. The above methods portray these as the steps are short and easy to follow. They are not only easy to set up, but they also give you different options for formatting.
Содержание
- Процедура создания
- Способ 1: автофигура
- Способ 2: стороннее изображение
- Способ 3: элемент ActiveX
- Способ 4: элементы управления формы
- Вопросы и ответы
Excel является комплексным табличным процессором, перед которым пользователи ставят самые разнообразные задачи. Одной из таких задач является создание кнопки на листе, нажатие на которую запускало бы определенный процесс. Данная проблема вполне решаема с помощью инструментария Эксель. Давайте разберемся, какими способами можно создать подобный объект в этой программе.
Процедура создания
Как правило, подобная кнопка призвана выступать в качестве ссылки, инструмента для запуска процесса, макроса и т.п. Хотя в некоторых случаях, данный объект может являться просто геометрической фигурой, и кроме визуальных целей не нести никакой пользы. Данный вариант, впрочем, встречается довольно редко.
Способ 1: автофигура
Прежде всего, рассмотрим, как создать кнопку из набора встроенных фигур Excel.
- Производим перемещение во вкладку «Вставка». Щелкаем по значку «Фигуры», который размещен на ленте в блоке инструментов «Иллюстрации». Раскрывается список всевозможных фигур. Выбираем ту фигуру, которая, как вы считаете, подойдет более всего на роль кнопки. Например, такой фигурой может быть прямоугольник со сглаженными углами.
- После того, как произвели нажатие, перемещаем его в ту область листа (ячейку), где желаем, чтобы находилась кнопка, и двигаем границы вглубь, чтобы объект принял нужный нам размер.
- Теперь следует добавить конкретное действие. Пусть это будет переход на другой лист при нажатии на кнопку. Для этого кликаем по ней правой кнопкой мыши. В контекстном меню, которое активируется вслед за этим, выбираем позицию «Гиперссылка».
- В открывшемся окне создания гиперссылки переходим во вкладку «Местом в документе». Выбираем тот лист, который считаем нужным, и жмем на кнопку «OK».
Теперь при клике по созданному нами объекту будет осуществляться перемещение на выбранный лист документа.
Урок: Как сделать или удалить гиперссылки в Excel
Способ 2: стороннее изображение
В качестве кнопки можно также использовать сторонний рисунок.
- Находим стороннее изображение, например, в интернете, и скачиваем его себе на компьютер.
- Открываем документ Excel, в котором желаем расположить объект. Переходим во вкладку «Вставка» и кликаем по значку «Рисунок», который расположен на ленте в блоке инструментов «Иллюстрации».
- Открывается окно выбора изображения. Переходим с помощью него в ту директорию жесткого диска, где расположен рисунок, который предназначен выполнять роль кнопки. Выделяем его наименование и жмем на кнопку «Вставить» внизу окна.
- После этого изображение добавляется на плоскость рабочего листа. Как и в предыдущем случае, его можно сжать, перетягивая границы. Перемещаем рисунок в ту область, где желаем, чтобы размещался объект.
- После этого к копке можно привязать гиперссылку, таким же образом, как это было показано в предыдущем способе, а можно добавить макрос. В последнем случае кликаем правой кнопкой мыши по рисунку. В появившемся контекстном меню выбираем пункт «Назначить макрос…».
- Открывается окно управление макросами. В нем нужно выделить тот макрос, который вы желаете применять при нажатии кнопки. Этот макрос должен быть уже записан в книге. Следует выделить его наименование и нажать на кнопку «OK».
Теперь при нажатии на объект будет запускаться выбранный макрос.
Урок: Как создать макрос в Excel
Способ 3: элемент ActiveX
Наиболее функциональной кнопку получится создать в том случае, если за её первооснову брать элемент ActiveX. Посмотрим, как это делается на практике.
- Для того чтобы иметь возможность работать с элементами ActiveX, прежде всего, нужно активировать вкладку разработчика. Дело в том, что по умолчанию она отключена. Поэтому, если вы её до сих пор ещё не включили, то переходите во вкладку «Файл», а затем перемещайтесь в раздел «Параметры».
- В активировавшемся окне параметров перемещаемся в раздел «Настройка ленты». В правой части окна устанавливаем галочку около пункта «Разработчик», если она отсутствует. Далее выполняем щелчок по кнопке «OK» в нижней части окна. Теперь вкладка разработчика будет активирована в вашей версии Excel.
- После этого перемещаемся во вкладку «Разработчик». Щелкаем по кнопке «Вставить», расположенной на ленте в блоке инструментов «Элементы управления». В группе «Элементы ActiveX» кликаем по самому первому элементу, который имеет вид кнопки.
- После этого кликаем по любому месту на листе, которое считаем нужным. Сразу вслед за этим там отобразится элемент. Как и в предыдущих способах корректируем его местоположение и размеры.
- Кликаем по получившемуся элементу двойным щелчком левой кнопки мыши.
- Открывается окно редактора макросов. Сюда можно записать любой макрос, который вы хотите, чтобы исполнялся при нажатии на данный объект. Например, можно записать макрос преобразования текстового выражения в числовой формат, как на изображении ниже. После того, как макрос записан, жмем на кнопку закрытия окна в его правом верхнем углу.
Теперь макрос будет привязан к объекту.
Способ 4: элементы управления формы
Следующий способ очень похож по технологии выполнения на предыдущий вариант. Он представляет собой добавление кнопки через элемент управления формы. Для использования этого метода также требуется включение режима разработчика.
- Переходим во вкладку «Разработчик» и кликаем по знакомой нам кнопке «Вставить», размещенной на ленте в группе «Элементы управления». Открывается список. В нем нужно выбрать первый же элемент, который размещен в группе «Элементы управления формы». Данный объект визуально выглядит точно так же, как и аналогичный элемент ActiveX, о котором мы говорили чуть выше.
- Объект появляется на листе. Корректируем его размеры и место расположения, как уже не раз делали ранее.
- После этого назначаем для созданного объекта макрос, как это было показано в Способе 2 или присваиваем гиперссылку, как было описано в Способе 1.
Как видим, в Экселе создать функциональную кнопку не так сложно, как это может показаться неопытному пользователю. К тому же данную процедуру можно выполнить с помощью четырех различных способов на свое усмотрение.
Еще статьи по данной теме:
Помогла ли Вам статья?
Home / Excel Basics / How to Add a Button in Excel
In Excel, users can add macro-enabled buttons on the worksheets and can run macros by just clicking on them.
Users can use these macro-enabled buttons to perform several different tasks like filtering data, selecting data, printing a worksheet, running formulas, and calculations just by clicking on the buttons.
Adding buttons and embedding the macros to them is easier. Excel has multiple ways to add the macro-enabled buttons to the worksheet. Below, we have some quick and easy ways mentioned for you to add the macro buttons in Excel.
Add Macro Buttons Using Shapes
Users can create buttons in excel using shapes. Creating buttons using shapes has more formatting options over the buttons created from Control buttons or ActiveX buttons. Users can change the design, color, font, and style of the button created using shapes.
- First, go to the “Insert” tab and then click on the “Illustrations” icon” then click on the “Shapes” option and select any rectangle button.
- After that, with the help of a mouse, draw the rectangular button on the worksheet.
- Now, to enter the text in the button, double-click on the button and insert the text.
- For formatting, go to the “Shape Format” tab and you will get multiple options for the formatting of the button.
- From here, you can format the font style, font color, button color, button effects, and much more.
- To edit the text, add the hyperlink, or add the macro, just right-click on the button and you will get the pop-up menu with multiple options.
- From here, you can edit the text, add the hyperlink, and can add the macro to the button.
- Now, select the “Assign Macro” option to add the macro to the button.
- Once you select the “Assign Macro” option, you will get the “Assign Macro” dialogue box opened.
- From here, select the macro and click OK.
- At this point, the button has become micro enabled, and when you move your cursor on the button, the cursor turns to the hand point cursor.
- To freeze the button movement, right-click on the button and select the “Format Shape” and select the option “Don’t move or size with cells”.
Add Macro Buttons Using Form Controls
- First, go to the “Developer” tab and click on the “Insert” icon under the “Control” group on the ribbon.
- After that, select the first button option from the “Form Controls” menu and draw a button on the worksheet.
- Now, select or type the macro name from the “Assign Macro” dialogue box and click OK.
- If you don’t have any macro created yet, you can click cancel to add the macro at a later stage.
- From here, right-click on the button and select “Assign Macro” to add the macro to the button if did not assign yet.
- To format the button font size, style, color, etc. select the “Format Control” option.
- Once you click on “Format Control”, you will get the “Format Control” window open and then can do the button font formatting.
- To freeze the button movement, select the “Properties” tab and select the option “Don’t move or size with cells” and click OK.
Add Macro Buttons Using ActiveX Controls
- First, go to the “Developer” tab and click on the “Insert” icon under the “Control” group on the ribbon.
- After that, select the first button option from the “ActiveX Controls” menu and draw a button on the worksheet.
- Now, to create and insert the macro to the button, click on the “View Code” icon to launch the VBA editor.
- Now, select the” CommandButton1” on the subprocedure and choose the “Click” option from the drop-down list on the right side of the editor.
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