You use a command button on an Access form to start an action or a set of actions. For example, you can create a command button that opens another form. To make a command button perform an action, you write a macro or event procedure and attach it to the command button’s On Click property. You can also embed a macro directly into the On Click property of the command button. This makes it possible to copy the command button to other forms without losing the functionality of the button.
What do you want to do?
-
Add a command button to a form by using a wizard
-
Create a button by dragging a macro to a form
-
Create a command button without using a wizard
-
Customize a command button
Add a command button to a form by using a wizard
By using the Command Button Wizard, you can quickly create command buttons that do a variety of tasks, such as closing the form, opening a report, finding a record, or running a macro.
-
Right-click the form in the Navigation Pane, and then click Design view on the shortcut menu.
-
On the Design tab, in the Controls group, ensure that Use Control Wizards is selected.
-
On the Design tab, in the Controls group, click Button.
-
In the design grid, click where you want the command button to be inserted.
The Command Button Wizard starts.
-
Follow the directions in the wizard. On the last page, click Finish.
The wizard creates the command button and embeds a macro in the button’s On Click property. The macro contains actions that perform the task you chose in the wizard.
View or edit a macro embedded in a command button
-
In the Navigation Pane, right-click the form that contains the command button, and then click Design View or Layout View on the shortcut menu.
-
Click the command button to select it, and then press F4 to display its property sheet.
-
On the Event tab of the property sheet, [Embedded Macro] should be displayed in the On Click property box. Click anywhere in the property box, and then click in the right side of the box.
The Macro Builder is displayed, showing the action or actions that make up the embedded macro.
Top of Page
Create a button by dragging a macro to a form
If you have already created and saved a macro, you can easily create a command button that runs the macro by dragging the macro from the Navigation Pane to a form that is open in Design view.
-
Open the form in Design view by right-clicking the form in the Navigation Pane, and then clicking Design View on the shortcut menu.
-
In the Navigation Pane, locate the macro that you want the new command button to run, and then drag the macro to the form.
Access automatically creates a command button and uses the macro name as the button’s caption. Access also inserts the macro name in the On Click property of the command button so that the macro runs when you click the button. Access uses a generic name for the button, so it is a good idea to type a more meaningful name in the button’s Name property. To display the property sheet for the command button while the form is open in Design view, click the button, and then press F4.
For more information about creating macros, see the article Create a user interface macro.
Top of Page
Create a command button without using a wizard
You can create a command button without using the Command Button Wizard. The process involves placing the button on the form and then setting a few properties.
-
Right-click the form in the Navigation Pane, and then click Design View on the shortcut menu.
-
On the Design tab, in the Controls group, ensure that Use Control Wizards is not selected.
-
On the Design tab, in the Controls group, click Button.
-
Click the location on the form where you want to place the command button.
Access places the command button on the form.
Because Use Control Wizards was not selected, Access does not perform any further processing. If the Command Button Wizard starts when you place the command button on the form, you can click Cancel in the wizard.
-
With the command button selected, press F4 to display its property sheet.
-
Click the All tab to display all the properties for the command button.
-
Set the properties to complete the design of the command button, as shown in the following table.
Property |
Description |
Name |
By default, Access gives a new command button the name Command, followed by a number; for example, Command34. Although it is not required, it is a good idea to change the name to something that reflects the function of the button (for example, cmdSalesReport or CloseFormButton). This helps you later, if you need to refer to the button in a macro or event procedure. |
Caption |
Type the label that you want displayed on the command button. For example, Sales Report or Close Form. Note: The caption is not displayed if a picture is specified in the Picture property. |
On Click |
Use this property to specify what happens when the command button is clicked. To set the property, click in the property box and then do one of the following:
|
For help with other properties not mentioned here, place the cursor in a property box and press F1.
Top of Page
Customize a command button
Access provides many ways to customize command buttons so that you can have the appearance and functionality you want on your form. For example, you can create a row of command buttons in a tabular or stacked arrangement, or you can make command buttons appear more like hyperlinks.
-
Right-click the form in the Navigation Pane, and then click Design View .
-
Do one of the following:
-
Create a horizontal (tabular) or vertical (stacked) layout of command buttons
You can add command buttons to a tabular or stacked layout to create a row or column of precisely aligned buttons. You can then reposition the buttons as a group, which makes it easier to modify forms. You can also apply formatting styles to the entire row or column of command buttons at the same time, and you can separate the buttons by using grid lines.
-
Right-click one of the command buttons that you want to add to the layout, and then point to Layout on the shortcut menu.
-
Click Tabular to start a horizontal row of buttons, or click Stacked to create a vertical column of buttons.
Access draws borders around the command button to indicate the layout. Each button is paired with a label that you cannot delete — however, you can shrink the label to a very small size, if it is not needed.
The following illustration shows a command button and its associated label in a tabular layout. Note how the label is in the next higher section — this keeps the labels from repeating for each detail record.
The following illustration shows a command button and its associated label in a stacked layout. In a stacked layout, the label and the button are always in the same section.
-
Add more command buttons to the layout by dragging them to the layout area. As you drag a command button over the layout area, Access draws a horizontal insertion bar (for a tabular layout) or a vertical insertion bar (for a stacked layout) to indicate where the command button will be placed when you release the mouse button.
When you release the mouse button, the control is added to the layout.
-
Move command buttons up a section or down a section within a tabular layout If you want to keep a command button in a tabular layout but want to move the command button to a different section of the form (for example, from the Detail section to the Form Header section), do the following:
-
Select the command button.
-
Click either Move Up or Move Down on the Arrange tab.
The command button moves up or down to the next section, but remains within the tabular layout. If there is a control already in the position that you are moving this control to, the two controls exchange places.
Note: The Move Up and Move Down commands are disabled for stacked layouts.
-
-
Move an entire layout of command buttons
-
Click any of the command buttons in the layout.
A layout selector appears at the upper left corner of the layout.
-
Drag the layout selector to move the layout to a new location.
-
-
-
Add gridlines to a layout of command buttons
-
Select any of the command buttons in the layout.
-
Click the Gridlines command on the Arrange tab, and then click the style of gridlines you want.
-
-
Make a command button transparent
By making a command button transparent, you can place it over any object on your form and give that object the functionality of a command button. For example, you have an image that you want to divide into separate, clickable areas, each of which starts a different macro. You can do this by placing multiple, transparent command buttons on top of the image.
-
Click the command button you want to make transparent, and then press F4 to display the command button’s property sheet.
-
On the Format tab of the property sheet, click in the Transparent property box.
-
Select Yes in the drop-down list.
You can still see the outline of the command button in Design view, but the button is invisible in Form view.
Note: Setting a command button’s Transparent property to Yes is not the same as setting its Visible property to No. Both operations hide the command button, but setting the Transparent property to Yes leaves the button enabled. Setting the Visible property to No disables the button.
-
-
Make a command button appear as a hyperlink
If you want, you can hide a command button but leave the caption visible. The result is something that looks like a label, but functions as a command button. You can also underline the text in the caption and change its color to make it appear as a hyperlink.
-
Click the command button to select it and press F4 to display its property sheet.
-
On the Format tab of the property sheet, click in the Back Style property box.
-
In the drop-down list, select Transparent.
The body of the command button is hidden, but its caption remains visible.
-
To underline or change the color of the text in the caption, use the tools in the Font group on the Design tab.
-
-
Create a Cancel button
-
Click the command button, and then press F4 to open its property sheet.
-
In the Cancel property box, click Yes.
When a command button’s Cancel property is set to Yes, and the form is the active form, a user can select the command button by clicking it, pressing the ESC key, or pressing ENTER when the command button has focus. When the Cancel property is set to Yes for any one command button, that property is automatically set to No for all other command buttons on the form.
To make a Cancel button cancel all the actions that have taken place in a form or dialog box, you need to write a macro or event procedure and attach it to the On Click property of the button.
Note: For a form that allows irreversible operations (such as deletions), it is a good idea to make the Cancel button the form’s default command button. To do this, set both the Cancel property and the Default property to Yes.
-
-
Display a picture on a command button In the command button’s Picture property box, type the path and file name for a picture file (such as a .bmp, .ico, or .dib file). If you are not sure of the path or file name, click to open the Picture Builder.
Click Browse to find the picture that you want to use or, alternatively, click one of the pictures in the Available Pictures list to preview the professionally-created pictures that you can use. If you find a picture you want, click OK to add it to the command button.
By default, Access sets the Picture Type property to Embedded. When you assign a graphic to a command button’s Picture property, using this setting creates a copy of the picture and stores it in the Access database file. Any subsequent changes to the original picture will not be reflected in the command button. To create a link to the original picture so that any changes to the picture will be reflected in the command button, change the Picture Type property to Linked. You must keep the original picture file in its original location. If you move or rename the picture file, Access displays an error message when you open the database, and the command button displays its caption instead of the picture.
-
Display both a picture and a caption on a command button
You can display both a caption and a picture on a command button. Use the following procedure:
-
Add a picture to the command button by using the procedure outlined earlier in this section.
-
Select the command button. If the property sheet is not already displayed, press F4 to display it.
-
On the Format tab of the property sheet, type the caption you want in the Caption property box.
-
Click the drop-down arrow in the Picture Caption Arrangement property box, and then select the arrangement you want. For example, to display the caption below the picture, select Bottom. To display the caption to the right of the picture, select Right. To make the arrangement dependent on the system locale, select General. By using this setting, the caption will appear on the right for languages that read from left to right, and it will appear on the left for languages that read from right to left.
-
-
Top of Page
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.
Contents
- 1 How do I get a command button?
- 2 How do I add a button to my toolbar in Excel?
- 3 How do I add a button in Excel without the Developer tab?
- 4 How do I change the command button in Excel?
- 5 How do you use command buttons?
- 6 What are the command buttons?
- 7 How do I add a button to the Quick Access Toolbar?
- 8 How do I add a new command to the Quick Access Toolbar?
- 9 What is launch button in Excel?
- 10 How do I create a command button to copy and paste data in Excel?
- 11 How do I create a Save button in Excel?
- 12 How do I select a button in Excel?
- 13 How do you add text to a button in Excel?
- 14 Where is command button Wizard in Access?
- 15 How do I add a submit Button to an Access form?
- 16 Where is command button keyboard?
- 17 What is command button control?
- 18 What are navigation buttons?
- 19 What is command button in laptop?
- 20 What is the command key on Windows 10?
How do I get a command button?
To add a command button to a form:
- In Form Layout view, select the Design tab, then locate the Controls group.
- Click the Button command.
- Choose the desired location for the command button, then click the mouse.
- The Command Button Wizard will appear.
How do I add a button to my toolbar in Excel?
Add a macro button to the Quick Access Toolbar
- Click File > Options > Quick Access Toolbar.
- In the Choose commands from list, click Macros.
- Select the macro you want to assign a button to.
- Click Add to move the macro to the list of buttons on the Quick Access Toolbar.
How do I add a button in Excel without the Developer tab?
Here are the steps to create the macro button:
- Draw a shape on the sheet (Insert tab > Shapes drop-down > Rectangle shape).
- Add text to the shape (Right-click > Edit Text | or double-click in the shape).
- Assign the macro (Right-click the border of the shape > Assign Macro…)
- Select the macro from the list.
- Press OK.
How do I change the command button in Excel?
Edit the text in a Form control
- Select the Form control. For more information, see Select or deselect controls on a worksheet.
- Right-click the selection, and then click Edit Text.
- Edit the text for the control.
- After you have finished editing the text, right-click the selection, and then click Exit Edit Text.
How do you use command buttons?
You use a command button on an Access form to start an action or a set of actions. For example, you can create a command button that opens another form. To make a command button perform an action, you write a macro or event procedure and attach it to the command button’s On Click property.
What are the command buttons?
A command button is a clickable image object used with graphical operating systems. For example, in Microsoft Windows, when clicking the close button (the X in the top-right of the window), Windows closes that open window.
How do I add a button to the Quick Access Toolbar?
On the ribbon, click the appropriate tab or group to display the command that you want to add to the Quick Access Toolbar. Right-click the command, and then click Add to Quick Access Toolbar on the shortcut menu.
How do I add a new command to the Quick Access Toolbar?
Click Customize the Quick Access Toolbar, and then click More Commands. In the Choose commands from list, click File Tab. Choose the command, and then click Add. Click OK.
What is launch button in Excel?
You can add up to 64 launch buttons to a custom toolbar. You can configure each button to run a different program or macro. For example, you are the manager of a government department. You keep the data source files for your reports in Microsoft Excel spreadsheets.
How do I create a command button to copy and paste data in Excel?
Create a Command Button to copy and paste data with VBA code
- Insert a Command Button by clicking Developer > Insert > Command Button (ActiveX Control).
- Draw a Command Button in your worksheet and right click it.
How do I create a Save button in Excel?
Adding “Save” Button in Excel
If you want to add a VBA save as button in Excel, you can do so using the “Developer” tab in the ribbon menu. Make sure you have enabled it by customizing the ribbon, and then click the “Insert” button; under “ActiveX Controls,” click the word “Button.”
How do I select a button in Excel?
On the Home tab, in the Editing group, click Find & Select, and then do either of the following:
- Click Select Objects, and then use the mouse pointer to draw a rectangle around the objects that you want to select.
- Click Selection Pane, and then use the pane to select one or more objects.
How do you add text to a button in Excel?
Link Button Text to a Cell
Click in the Formula Bar, and type an equal sign: = Click on cell E2, which has the text for the button, and press Enter.
Where is command button Wizard in Access?
In Form Layout view, select the Design tab, then locate the Controls group. Click the Button command. Choose the desired location for the command button, then click the mouse. The Command Button Wizard will appear.
How do I add a submit Button to an Access form?
Add a command button to your Access form without programming
- Open the form in design view.
- Click the Command button in the Toolbox.
- Click and drag in the form where you want the button to be located.
- Select Form Operations under categories.
- Select Close Form under Actions.
- Click Next.
Where is command button keyboard?
On a PC keyboard the Command key is either the Windows key or the Start key.
What is command button control?
Command buttons are used to issue commands in a form. The OK and Cancel buttons often seen in Windows dialogs are command buttons, for example.
What are navigation buttons?
Each button corresponds to the direction that you can move in a menu.For example, to move right in a menu, press the navigation button that is located on the right side. If you want to move down in a menu, press the navigation button that is located on the bottom.
What is command button in laptop?
The Command key’s purpose is to allow the user to enter keyboard commands in applications and in the system. An “extended” Macintosh keyboard—the most common type—has two command keys, one on each side of the space bar; some compact keyboards have one only on the left.
What is the command key on Windows 10?
The Most Important (NEW) Keyboard Shortcuts for Windows 10
Keyboard shortcut | Function / Operation |
---|---|
Windows key + CTRL + F4 | Close the current virtual desktop |
Windows key + A | Open Action center on the right of the screen |
Windows key + S | Open Search and place the cursor in the input field |
1. Add Excel Command Button from Quick Access Toolbar
This is Applicable for Excel 2007 and above versions.
This page has quick tips to insert command button in Excel from (1) quick access toolbar & (2) developer tab. Follow these steps to know more…
1. To insert the command button or any other controls, add “Insert Controls” in the Quick Access Toolbar as explained in this post.
Learn this: How To Add Insert Controls – Button in Quick Access Toolbar
2. Once the Control is added, click on “Insert Controls” to view what are the available commands that can be inserted in worksheet.
3. Click on Commands Button and draw the control on Excel Sheet.
4. Double click on Command after adding, to insert VBA Macro code for the newly inserted control.
Using this method, Form Controls & ActiveX Controls can be added to a Excel worksheet or MS Word document.
2. Adding Command Button From Developer Tab
To add controls to Excel sheet & control the macro code, add developer tab to Excel as explained in this link.
Once developer tab appears on Excel menu, follow these steps.
- Click ‘Developer’ tab in Menu.
- Select ‘Insert Controls’.
- Click ‘Command Button’ in Activex controls.
- Click & Draw command button on Excel Sheet.
- Double click on command button to add VBA code.
Double clicking on Activex control will open vb editor to write the code behind the control button. If we add form control, we can assign a macro to the control.
Enable design mode to write the code. Disable design mode, click on the control to test whether the control is able to execute the vba code properly.
Remember to save the workbook with .xlsm (macro enabled Excel) mode. Then only the vba code project will be saved along with Excel. Else you will end up in loosing the code.
Элемент управления пользовательской формы CommandButton, используемый в VBA Excel для запуска процедур и макросов. Свойства кнопки, примеры кода с ней.
UserForm.CommandButton – это элемент управления пользовательской формы, предназначенный исключительно для запуска процедур и макросов VBA Excel.
Для запуска процедур и макросов обычно используется событие кнопки – Click.
Свойства элемента CommandButton
Свойство | Описание |
---|---|
AutoSize | Автоподбор размера кнопки. True – размер автоматически подстраивается под длину введенной надписи (заголовка). False – размер элемента управления определяется свойствами Width и Height. |
BackColor | Цвет элемента управления CommandButton. |
Caption | Надпись (заголовок) – текст, отображаемый на кнопке. |
ControlTipText | Текст всплывающей подсказки при наведении курсора на кнопку. |
Enabled | Возможность взаимодействия пользователя с элементом управления CommandButton. True – взаимодействие включено, False – отключено (цвет надписи становится серым). |
Font | Шрифт, начертание и размер текста надписи. |
Height | Высота элемента управления. |
Left | Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления. |
Picture | Добавление изображения вместо текста заголовка или дополнительно к нему. |
PicturePosition | Выравнивание изображения и текста на кнопке. |
TabIndex | Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с 0. |
Top | Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления. |
Visible | Видимость элемента управления CommandButton. True – элемент отображается на пользовательской форме, False – скрыт. |
Width | Ширина элемента управления. |
WordWrap | Перенос текста заголовка на новую строку при достижении ее границы. True – перенос включен, False – перенос выключен. |
В таблице перечислены только основные, часто используемые свойства кнопки. Все доступные свойства отображены в окне Properties элемента управления CommandButton.
Пример кнопки с надписью и изображением
Примеры кода VBA Excel с кнопкой
Изначально для реализации примеров на пользовательскую форму UserForm1 добавлена кнопка CommandButton1.
Пример 1
Изменение цвета и надписи кнопки при наведении на нее курсора.
Условие примера 1
- Действия при загрузке формы: замена заголовка формы по умолчанию на «Пример 1», замена надписи кнопки по умолчанию на «Кнопка», запись цвета кнопки по умолчанию в переменную уровня модуля.
- Сделать, чтобы при наведении курсора на кнопку, она изменяла цвет на зеленый, а надпись «Кнопка» менялась на надпись «Нажми!»
- Добавление кода VBA Excel, который будет при удалении курсора с кнопки возвращать ей первоначальные настройки: цвет по умолчанию и надпись «Кнопка».
Решение примера 1
1. Объявляем в разделе Declarations модуля пользовательской формы (в самом начале модуля, до процедур) переменную myColor:
2. Загружаем пользовательскую форму с заданными параметрами:
Private Sub UserForm_Initialize() Me.Caption = «Пример 1» With CommandButton1 myColor = .BackColor .Caption = «Кнопка» End With End Sub |
3. Меняем цвет и надпись кнопки при наведении на нее курсора мыши:
Private Sub CommandButton1_MouseMove(ByVal _ Button As Integer, ByVal Shift As Integer, _ ByVal X As Single, ByVal Y As Single) With CommandButton1 .BackColor = vbGreen .Caption = «Нажми!» End With End Sub |
4. Возвращаем цвет и надпись кнопки при удалении с нее курсора мыши:
Private Sub UserForm_MouseMove(ByVal _ Button As Integer, ByVal Shift As Integer, _ ByVal X As Single, ByVal Y As Single) With CommandButton1 .BackColor = myColor .Caption = «Кнопка» End With End Sub |
Все процедуры размещаются в модуле пользовательской формы. Переменная myColor объявляется на уровне модуля, так как она используется в двух процедурах.
Пример 2
Запуск кода, размещенного внутри процедуры обработки события Click элемента управления CommandButton:
Private Sub CommandButton1_Click() MsgBox «Код внутри обработки события Click» End Sub |
Пример 3
Запуск внешней процедуры из процедуры обработки события Click элемента управления CommandButton.
Внешняя процедура, размещенная в стандартном модуле проекта VBA Excel:
Sub Test() MsgBox «Запуск внешней процедуры» End Sub |
Вызов внешней процедуры из кода обработки события Click
- с ключевым словом Call:
Private Sub CommandButton1_Click() Call Test End Sub |
- без ключевого слова Call:
Private Sub CommandButton1_Click() Test End Sub |
Строки вызова внешней процедуры с ключевым словом Call и без него – равнозначны. На ключевое слово Call можно ориентироваться как на подсказку, которая указывает на то, что эта строка вызывает внешнюю процедуру.
Содержание
- Command Buttons in VBA for Excel
- 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?
- Excel VBA UserForm CommandButton
- VBA Reference
- 120+ Project Management Templates
- VBA ActiveX CommandButton Control on the UserForm
- Add dynamic CommandButton Control on the UserForm using VBA
- Procedure to call in the Command Button :
- Delete CommandButton Control on the UserForm using VBA
Command Buttons in VBA for Excel
In the toolbox the command button has this icon . The command button is a very active control and there is always VBA code behind it.
The command buttons are usually placed at the bottom of the form and serve to complete the transaction for which the form has been created. The caption of these buttons are usually «Go» , «Run» , «Submit» , «Cancel» , etc.
Among the other properties of the command button are:
— WordWrap to be able to write more that one line on a button,
— ControlTipText which generates a small comment box when the user moves the mouse over the control. You can use this property to give explanations and instructions about the command button,
Adding a Command Button to a Userform
To add a command button to a userform you left click on its icon in the toolbox. You move the cursor to the userform, you click again and the command button appears. You can then resize it to your liking. If you double click on the command button icon in the toolbox you can then click on the form as many times as you need command buttons. When you are finished adding command buttons just click once on the command button icon of the toolbox.
Most of the VBA code (VBA sentences) is created within the command button when you develop simple userforms. Here are two exercises creating VBA code within the command button.
We hope you have enjoyed this introduction to lesson 28
for more on this topic and a complete course on Excel macros download the
Tutorial on Excel Macros
Источник
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.
Источник
Excel VBA UserForm CommandButton
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
50+ Excel Templates
50+ PowerPoint Templates
25+ Word Templates
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
CommandButton is one of the UserForm control. You can select and drag CommandButton on the UserForm. CommandButton is used to run or execute a macro or procedure. It performs a task or an action when a user clicks on a command button. Command Button can be used on the WorkSheet or UserForm. Please find more details about ActiveX CommandButton Control in the following chapter. You can see how we are adding or deleting command button on the UserForm or Worksheet.
VBA ActiveX CommandButton Control on the UserForm
Please find more details about VBA ActiveX Command Button Control on the UserForm.
-
- Go To Developer Tab and then click Visual Basic from the Code or Press Alt+F11.
- Go To Insert Menu, Click UserForm. Please find the screenshot for the same.
-
- Drag a CommandButton on the Userform from the Toolbox. Please find the below screenshot for the same.
-
- Now double click on the Command Button, which is dragged on the UserForm .
- Now you can see the following code in the VBA Editor window.
-
- Now add the following code to the in between above procedure.
Code:
-
- Now, Press ‘F5’ to run the code. You can see the following Output. It is shown in the following Screen Shot.
output:
Add dynamic CommandButton Control on the UserForm using VBA
Please find the following steps and example code, it will show you how to add dynamic Command Button control on the userform.
-
- Add command button on the userform from the toolbox.
- Right click on the command button, click properties
- Change the command button caption to ‘Create_CommandButton’
- Double click on the command button
- Now, it shows the following code.
-
- Call the below procedure named ‘Add_Dynamic_CommandButton ’ and find the below procedure to run.
Procedure to call in the Command Button :
-
- Now, click F5 to run the macro, click ‘Create_CommandButton’ button to see the result.
- You can see the created dynamic Command Button which is shown in the following screen shot.
output:
Delete CommandButton Control on the UserForm using VBA
Please find the below code, it will show you how to delete or remove a command button on the UserForm. In the below example, its deleting the command button named ‘New Button’ which is on the UserForm named ‘UserForm4’. We can use Remove method to delete the controls which are created during run time. Controls which are created during design time cannot be deleted using this method. Please find the below example and screen shots for better understand.
Code 1: Adding CommandButton During Run Time
Please find the below screen shot for your reference for the above macro and its output.
When we click on Add Command Button:
Code 2: Deleting or Removing CommandButton which is created during run time.
Please find the below screen shot for your reference for the above macro and its output.
When we click on Delete Command Button:
Источник