Buttons for excel macro

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.

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

Хитрости »

1 Май 2011              357301 просмотров


Как создать кнопку для вызова макроса на листе?

После создания макроса часто возникает вопрос: а как его теперь запустить? Можно, конечно, нажать сочетание клавиш Alt+F8 и выбрать нужный макрос, но…Во-первых это не всегда удобно, особенно если макросов больше 5-ти. Во-вторых: если файлом с макросом будут пользоваться другие люди, не умеющие всего этого делать, придется объяснять им все это, что тоже не очень здорово — многие просто будут вспоминать Вас не очень хорошими словами :-)

Но к нашему общему счастью в Excel есть замечательная возможность создавать элементы, с помощью которых можно вызвать макрос просто нажатием на них. Кроме того это можно сделать еще и красиво. В данной статье я опишу как можно сделать красивые и не очень кнопки на листе для вызова имеющихся у Вас макросов.

Итак, ниже на рисунке Вы можете видеть четыре варианта кнопочек для вызова макроса.


Кнопка элемент ActiveX
Данная кнопка считается устаревшей и не рекомендуется к использованию. Вот одна из причин, почему лично я не использую такие кнопки в своих проектах: Элементы ActiveX перестали работать или ведут себя непредсказуемо. Т.е. создав такую кнопку, можно заранее готовиться к тому, что в какой-то момент кнопка просто перестанет работать.
Однако многие все же предпочитают использовать именно её(либо не знают, что можно по-другому), даже не смотря на то, что назначить для этой кнопки макрос кому-то покажется сложнее, чем для остальных рассматриваемых в данной статье.
Как создать кнопку ActiveX:

  • В версии Excel 2007 и выше доступ к этим элементам возможен с вкладки Разработчик (Developer):
    Отобразить вкладку Разработчик (Developer) (если еще не отображена)
    Excel 2007: Параметры Excel(Excel Options)Основные(Popular)— галочка напротив Показывать вкладку Разработчик на ленте(Show Developer Tab on Ribbon)
    Вкладка Разработчик
    Excel 2010: Файл (File)Параметры (Options)Настройка ленты (Customize Ribbon)— галочка напротив Разработчик (Developer)
    Теперь переходим на эту вкладку и видим команду Вставить (Insert). Жмем и у нас выпадает меню с возможностью выбрать элементы:

    В категории «Элементы ActiveX» выбираем самый первый(это серенький кирпичик). Курсор приобретет вид тоненького крестика. Теперь нам надо на листе нарисовать кнопку. Все, наша кнопка готова.
  • Для обладателей версии Excel 2003 не намного все проще. Сначала необходимо отобразить панель инструментов Элементы управления. Делается это следующим образом: правая кнопка мыши на панели меню- Настройка— вкладка Панели инструментов

    На данной панели так же выбираем серенький кирпичик и рисуем кнопку.

    Теперь осталось назначить созданной кнопке макрос. Для этого, не выходя из режима конструктора (в Excel 2007 он на вкладке Разработчик (Developer), а в Excel 2003 на панели Visual Basic —Режим конструктора), производим двойной щелчок по созданной кнопке — Excel перейдет в режим редактирования кода из интерфейса VBA и автоматом будет создана пустая процедура: Private Sub CommandButton1_Click(). CommandButton1 — это имя нашей кнопки. У Вас оно может отличаться. Теперь внутрь процедуры мы вписываем строку вызова макроса — Call Макрос1. Вместо Макрос1, естественно, имя необходимого макроса.

    Private Sub CommandButton1_Click()
        Call Макрос1
    End Sub

    А вот на этом, пожалуй, все для данного элемента.


Для остальных элементов принцип назначения макроса одинаков, а поэтому сначала рассмотрим создания каждого из них, а после уже способ назначения макроса

Кнопка элемент управления формы
Здесь чуть проще. Для того, чтобы добавить данный элемент на лист для начала придется выполнить примерно те же действия, что и для создания кнопки ActiveX.
Для пользователей 2007 Excel и выше отобразить вкладку Разработчик (Developer) на ленте(если еще не отображена). Только выбор кнопки теперь надо делать из первой группы — Элементы управления форм.
для пользователей 2003 сначала надо добавить панель инструментов Формы: правая кнопка мыши на панели- Настройка— вкладка Панели инструментов. Жмем на первый элемент — серенький кирпичик. Рисуем. Как только Вы нарисуете кнопку появится меню с просьбой назначить макрос на кнопку(рис.1). Вы можете сделать это сразу, либо позже.


Автофигура
Для пользователей Excel 2007-2010: вкладка Вставка (Insert)Фигуры (Shapes). Просто выбираете любую понравившуюся фигуру.
Для пользователей Excel 2003 для начала необходимо отобразить панель инструментов Рисование, как было описано выше. Там выбрать пункт Автофигуры и выбрать из категории понравившуюся фигуру.
После создания фигуры можно кликнуть по ней правой кнопкой мыши, выбрать Формат фигуры и изменить там оформление фигуры: цвет заливки, прозрачность, обводку и еще разные опции — здесь все зависит от фантазии.


Рисунок
для пользователей Excel 2007: вкладка Вставка (Insert)Рисунок (Picture). Выбираете любой рисунок из имеющихся на компьютере.
Для пользователей 2003 сначала необходимо отобразить панель инструментов Рисование(если не отображена). Далее жмем на кнопку Добавить рисунок из файла .


как назначить макрос
Для Кнопки элемент управления формы, Автофигуры и Рисунка процедура назначения макроса совершенно одинакова: жмем правой кнопкой мыши на  элементе управления формы, фигуре или картинке — Назначить макрос.

Появится диалоговое окно выбора макросов. Выбираете нужный и жмете Ок. Все, наша кнопка готова и по её нажатии выполняется выбранный нами макрос.
рис.1

Таким же образом можно назначить макрос не только указанным элементам, но и Диаграмме, элементу Надпись, обекту WordArt, рисунку SmartArt.


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

We can automate the most common tasks in Excel to avoid unnecessary time consumption. Regarding automation, VBA macros are the way to go forward in Excel. Once the macro coding is completed, we need to execute that program to get the assigned job done. You must have already seen a button that can do the job in many of the worksheets, so once the programming is done, we can assign that work to one of the buttons so that the given job will be executed by click of the button. So in this article, we will take you through creating an Excel button to perform the task.

Table of contents
  • Create a Macro Button in Excel
    • 3 Methods to Create Button in Macro Excel?
      • #1 – Using Shapes
      • #2 – Using Form Control Shapes & Active X
    • Things to Remember
    • Recommended Articles

3 Methods to Create Button in Macro Excel?

As we know, macro coding is the perfect way to automate tasks. However, there is another small thing we can do to execute that code. Macro and buttons are the ideal combinations. It is like a “typical Indian marriage of boy likes a girl and girl likes a boy.” With just the click of the button, we can execute hundreds of lines, so some of the complex reports can be automated and handed over to our team members. But then, we have to click the button to get the job done.

So, we can create a button in three ways in Excel. Those are below:

  1. Shapes
  2. Active X Control
  3. Form Control in ExcelExcel Form Controls are objects which can be inserted at any place in the worksheet to work with data and handle the data as specified. These controls are compatible with excel and can create a drop-down list in excel, list boxes, spinners, checkboxes, scroll bars.read more

Excel-Create-Button

We will see each one of them in detail now.

You can download this Create Button Excel Template here – Create Button Excel Template

#1 – Using Shapes

The best and easiest way to create a button to assign a macro is using “Shapes” in Excel. We can insert a wide variety of shapes in Excel, and also we can format these shapes as we would like to make them look.

Before inserting shapes, below is the macro we had written to filter values in the below data.

Create Button Example 1

We have data in columns from A to E. In the G2 cell, we have created a drop-down list of all the card types, the card type that we choose in the G2 cell should be filtered out in the data. For this, below is the excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
code we have written.

Code:

Sub Filter_Values()

 Dim LR As Long
 Dim LC As Long
 Dim Rng As Range

 LR = Cells(Rows.Count, 1).End(xlUp).Row
 LC = Cells(5, Columns.Count).End(xlToLeft).Column

 Set Rng = Cells(5, 1).Resize(LR, LC)
 Rng.AutoFilter Field:=4, Criteria1:=Range("G2").Value

End Sub

Upon running the above code, it will filter the values which are selected in the cell G2 cell. Every time we need to open the Visual Basic EditorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more, and we need to run the code.

So, now we will insert shapes to assign the macro.

Follow the below-given steps to assign macro to shape.

  1. We must first go to the “Insert” tab in Excel and find the “Shapes ” option.

    Create Button Example 1-1

  2. Once we click on the ” Shapes ” drop-down list, we see many shape options. Select any of the shapes and draw on the worksheet.

    Create Button Example 1-3

  3. After adding the shapes, we need to enter some text values, so right-click on the shape and choose “Edit Text.”

    Create Button Example 1-4

  4. We must enter the text as we would like to convey the message to the user.

    Create Button Example 1-5
    It is the default view of the shape.

  5. We can format the shape under the “Format” tab.

    Create Button Example 1-6

  6. Once the proper formatting is given to the shape, we need to click and choose “Assign Macro.”

    Create Button Example 1-7

  7. Once the proper formatting is given to the shape, right-click and choose “Assign Macro.” Next, we must select the macro we would like to assign to the shape.

    Create Button Example 1-9

  8. Now click on “OK,” Currently, the macro has been assigned to the shape.

    We see the hand pointer indicating the click option when we hover on the shape. If we click, it will execute the assigned macro, and the value in cell G2 will be filtered.
    Create Button Example 1-11

#2 – Using Form Control Shapes & Active X

Under the the developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more, we have an option called “Insert.” Under this, we have “Form Control” and “Active X Control.”

Use Form Control 1

From “Form Controls,”  we must select the “Button” option.

Use Form Control 1-1

Then, draw this on the worksheet, and immediately we will get a list of macros.

Use Form Control 1-2

We need to choose the macro we would like to assign and click on “OK” to close the above window.

As a result, now, a button is created to run the macro.

Use Form Control 1-3

Like this, we can create a button in Excel to execute the macro.

Things to Remember

  • The Active X Control button requires further coding knowledge, so not covered in this article.
  • The basic difference between “Shape” and “Form Controls” is the formatting and style they look like.

Recommended Articles

This article has been a guide to Create Button Macro in Excel. Here, we discuss the top 3 methods using shapes, active X control, form controls, examples, and downloadable Excel templates. You may learn more about Excel from the following articles: –

  • VBA Macros
  • Record Macros in Excel
  • VBA Tutorial

Button in Excel as a link to a cell, a tool, or a created macro, makes the work in the program much easier. Most often, it is a graphic object with an assigned macro or a hyperlink. Let’s consider how to make such a button in Microsoft Excel program.



How to make a button on the Excel sheet

The essence of the work lies in creating a graphic object and assigning a macro or hyperlink to it. Let’s consider the order of actions in detail.

Ways to create a graphic object in Excel:

  1. An ActiveX control command button. Go to the «DEVELOPER» tab. Press the «Insert» ActiveX button. The menu with a set of items to insert will open. You need to select the first ActiveX element, that is depicted in in the form of a gray brick. Now draw the button of the required size using the cursor.
  2. ActiveX control.

  3. A Form control button. Again, go to the «DEVELOPER» tab. Open the menu of the «Insert» tool. Now select the «Button (Form Control)» element from the first group (the same gray-colored brick). Then draw the button. The window for assigning a macro opens immediately: you can assign it right now or later at your option.
  4. Form Control.

  5. A shape button. Go to the «INSERT» tab. In the «Recently Used Shapes» menu, select the appropriate shape. Draw this shape. You can right-click the finished shape and change its formatting.
  6. Draw this shape.

  7. A picture button. Go to the «INSERT» tab. In the «Illustrations» menu, select the «Pictures» tool. The options that are available on the computer will be offered to choose from.

picture button.

The graphic object has been created. Now you need to make it “able to work”.



How to make a button with macro in Excel

For example, you have created a macro to perform a specific task. To run it, you need to go to the «DEVELOPER» menu every time, which is inconvenient. It is much easier to create a special button.

If you have used an ActiveX control, then:

enter a command.

For other graphic objects, the macro is assigned in the same way. The procedure is even simpler. You need to right-click on the drawn button or picture and select the «Assign Macro» tool.

Assign Macro.

Other options of using buttons

With the help of buttons, you can not only execute created macros, but also move to a certain cell, another document, or another sheet in Excel program. Let us consider this matter in detail.

Draw a graphic object and highlight it. Find the «Hyperlink» on the «INSERT» tab.

Hyperlink.

After clicking, a window will be opened. This window is intended for creating a connection between the button and a file, web page, e-mail, new document, and location in the current Excel document.

opened.

It is enough to choose the desired option and specify the path to it. This method doesn’t require writing macros and provides the user with a wide range of opportunities.

Similar tasks can be performed with the help of macros. For example, for a user to go to a certain cell (M6) when clicking the button, the following code should be written:

Sub Macro1()
Range(«M6»).Select
End Sub

Similarly, you can assign a macro to a chart, WordArt and SmartArt objects.

How to make the sort button for tables in Excel

For an illustrative example, create a test table as in the figure:

illustrative example.

  1. Instead of the table column headers, add shapes that will serve as buttons for sorting by the columns of the table.
  2. column headers.

  3. In the Visual Basic mode (ALT + F11), insert the new module (Module1) in the Modules folder. To do this, right-click on the folder and choose Insert-Module.
  4. Insert-Module.

  5. Double click on Module1 and enter the following code into it:


    Sub Macro1()
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A2:A6"), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SetRange Range("A2:D6")
            .Apply
        End With
    End Sub
    Sub Macro2()
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B2:B6"), _
            SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SetRange Range("A2:D6")
            .Apply
        End With
    End Sub
    Sub Macro3()
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("C2:C6"), _
            SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SetRange Range("A2:D6")
            .Apply
        End With
    End Sub
    Sub Macro4()
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("D2:D6"), _
            SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SetRange Range("A2:D6")
            .Apply
        End With
    End Sub

    Note. Red text indicates different parameters for each column.

  6. Assign to each shape its own macro: Macro1 for «NAME» Macro2 for «May», and so on.

That’s all, now you just need to click on the header and the table will sort the data to a particular column. For convenience, Macro1 sorts the column «NAME» in ascending order due to Order:=xlAscending parameter. All other columns have assigned macros (2,3,4) with Order:=xlDescending parameter, which sets the sort type in descending order. This is done in order to show the user in which month more goods have been sold.

Download example of the sort button

Note. Such simple macros can be created in automatic mode without programming or without writing VBA (Visual Basic for Application) code, using the «Record Macro» tool.

Понравилась статья? Поделить с друзьями:
  • Button and vba for excel
  • But это linking word
  • But word travels fast
  • But the word of the lord
  • But speak the word only