Macros for all excel workbooks

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

When you first create a macro in a workbook, it works only in that workbook. But what if you want to use the macro in other workbooks? To make your macros available every time you open Excel, you can create them in a workbook called Personal.xlsb. That’s a hidden workbook stored on your computer, which opens in the background every time you open Excel.

Macros and VBA tools can be found on the Developer tab, which is hidden by default, so the first step is to enable it. For more information, see Show the Developer tab.

Developer tab on the ribbon

Next, create a macro. We’ll record a macro that does nothing, but will create the Personal Macro workbook.

You can learn more about creating macros in Quick start: Create a macro.

  1. Go to the Developer tab, and click Record Macro.

    Code group on the Developer tab

  2. In the Record Macro dialog box, don’t bother entering a name for the macro in the Macro name box. You can accept the name that Excel gives you, such as Macro1, since this is just a temporary macro.

    When you do start creating macros of your own, you’ll want to give them descriptive names, so you know what they do.

  3. In the Store macro in box, pick Personal Macro Workbook > OK. This is the most important step, because if you don’t already have a Personal Macro Workbook, Excel will create one for you.

  4. Click Developer > Stop Recording, and Excel will have created your Personal Macro worbook.

  5. When you close the workbook, you’ll be prompted to save both the workbook, and the Personal Macro workbook.

To see the macro you created:

  1. Go to Developer > Visual Basic to launch the Visual Basic Editor (VBE), which is where your macros are stored.

  2. You can find your Personal Macro workbook in the Project Explorer pane on the left hand side. If you don’t see it, go to View > Project Explorer.

  3. Double-click on the VBA Project (PERSONAL.xlsb) folder > Modules > Module1, and you’ll find the empty Macro1 that you recorded. You can delete it, or keep it to add code to later.

    Note: When you record a macro in a new instance of Excel, VBA will automatically create a new Module folder and increment its number. So if you already have Module1 and Module2, VBA will create Module3. You can rename Modules in the Properties window beneath the Project Explorer, so they better reflect what the macros inside them do.

Moving macros from one computer to another

Your Personal.xlsb file is stored in a folder called XLSTART. If you want to share your macros with someone else, you can copy it to the XLSTART folder on other computers, or copy some or all of its macros to the Personal.xlsb file on other computers. You can search for XLSTART in Windows Explorer to locate it.

If you have one or just a few macros that you want to share with others, you can send them the workbook that contains them. You can also make the workbook available on a shared network drive or from a SharePoint Services library.

For more information about copying a macro from one workbook to another, see Copy a macro module to another workbook.

Make sure the Developer tab is visible on the ribbon. By default, the Developer tab is not visible, so do the following:

  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.

Next, create a macro. We’ll record a macro that does nothing, but will create the Personal Macro workbook.

You can learn more about creating macros in Quick start: Create a macro.

  1. Go to the Developer tab, and click Record Macro.

  2. In the Record Macro dialog box, don’t bother entering a name for the macro in the Macro name box. You can accept the name that Excel gives you, such as Macro1, since this is just a temporary macro.

    When you do start creating macros of your own, you’ll want to give them descriptive names, so you know what they do.

  3. In the Store macro in box, pick Personal Macro Workbook > OK. This is the most important step, because if you don’t already have a Personal Macro Workbook, Excel will create one for you.

  4. Click Developer > Stop Recording, and Excel will have created your Personal Macro worbook.

  5. When you close the workbook, you’ll be prompted to save both the workbook, and the Personal Macro workbook.

To see the macro you created:

  1. Click Developer > Visual Basic to launch the Visual Basic Editor (VBE), which is where your macros are stored.

  2. You can find your Personal Macro workbook in the Project Explorer pane on the left hand side. If you don’t see it, go to View > Project Explorer.

  3. Double-click on the VBA Project (PERSONAL.xlsb) folder > Modules > Module1, and you’ll find the empty Macro1 that you recorded. You can delete it, or keep it to add code to later.

Note: When you record a macro in a new instance of Excel, VBA will automatically create a new Module folder and increment its number. So if you already have Module1 and Module2, VBA will create Module3. You can rename Modules in the Properties window beneath the Project Explorer, so they better reflect what the macros inside them do.

Moving macros from one computer to another

Your Personal.xlsb file is stored in a system startup folder. If you want to share your macros with someone else, you can copy Personal.xlsb to the startup folder on other computers, or copy some or all of its macros to the Personal.xlsb file on other computers. In Finder select Go, then hold down the Option key, and select Library. In the Library pane, navigate to: Group Containers > xyz.Office (where xyz be a text string, like «UBF8T346G9») > User Content > Startup > Excel. Paste your Personal.xlsb file into the Excel folder.

If you have one or just a few macros that you want to share with others, you can send them the workbook that contains them. You can also make the workbook available on a shared network drive or from a SharePoint Services library.

For more information about copying a macro from one workbook to another, see Copy a macro module to another workbook.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

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.

When you create/record a macro in a workbook in Excel, it can only be used in that workbook.

But what if you have a list of useful Excel macros that you want to use in all the workbooks?  In such a case, it’s a good idea to save these in your Personal Macro Workbook.

Doing this would allow you to access the macro code from any workbook on your system.

This will save time as you don’t have to recreate the same macros again and again for every workbook. Instead, you can just create it once, store it in the personal macro workbook, and access it from any workbook.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

What is a Personal Macro Workbook?

A Personal Macro Workbook is a hidden workbook in your system that opens whenever you open the Excel application.

Related: How to Automatically Open Specific Excel Files on Startup

It’s a place where you can store macro codes and then access these macros from any workbook. It’s a great place to store those macros that you want to use often.

To give you an example, suppose you regularly get data from your colleagues, and you’re required to clean the data and format it. Since you need to follow the same steps every time, you can create a macro to do this and save it in the Personal Macro Workbook.

Now, whenever you get the Excel file, you just need to run the macro (which is stored in the personal workbook and can be accessed from any workbook), and you’re done.

Where Can I Find the Personal Macro Workbook?

By default, the personal macro workbook doesn’t exist. You need to first create it.

Here are the steps to create a Personal Macro Workbook in Excel:

Note: If you can’t see the developer tab in the ribbon, here are the steps to enable it.

Doing this would create a new workbook with the name PERSONAL.XLSB and store the macro in this workbook.

Since we did absolutely nothing, the macro has no code in it. This was done to create the Personal Macro Workbook.

Now that the Personal Macro Workbook is created, you need to Close all the open workbooks. Doing this would show a prompt as shown below:

Click on Save to create the Personal Macro Workbook

Select Save.

When this is done, Excel will create and store the PERSONAL.XLSB file in the start folder, where it would automatically open in the backend whenever you open Excel.

How to Copy Macros in the Personal Macro Workbook?

Once the PERSONAL.XLSB file is created and saved, you can copy macros that you wish to reuse again.

Here are the steps to copy macros in the Personal Macro Workbook:

The above steps would save the macros you want to reuse in the Personal Macro Workbook.

Also read: How to Remove Macros From an Excel Workbook

How to Use Macros Stored in Personal Macro Workbook?

Suppose you have a list of macros saved in the Personal Macro workbook and you want to use it on a new Excel file you get.

Here are the steps to do this:

  • Go to the Developer tab.
  • Click on Macros.
  • In the Macro dialog box, select the macro that you want to run.
  • Click on Run.

Note that the macro dialog box shows you the list of all the macros that are available for use in the open workbook. This would include the macros stored in the workbook as well as the ones stored in the Personal Macro Workbook.

You can also run a macro by assigning a keyboard shortcut to the macro or insert a shape/button and assign the macro to it.

You can also use the Personal Macro Workbook to store custom functions (user-defined functions) created in VBA.

You May Also Like the Following Excel Tutorials:

  • Working with Cells and Ranges in Excel VBA.
  • Working with Worksheets in Excel VBA.
  • Working with Workbooks in Excel VBA.
  • Creating a User Defined Function in Excel using VBA.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • Using Loops in Excel VBA.
  • If Then Else Statement in Excel VBA.
  • How to Create and Use an Excel Add-in.

Содержание

  • 1 Как сохранить макрос в личную книгу макросов
    • 1.1 Как создать Личную Книгу Макросов
    • 1.2 Как использовать Личную Книгу Макросов
    • 1.3 Где хранится Личная Книга Макросов
    • 1.4 P.S.
    • 1.5 Ссылки по теме

Большинство пользователей Excel знают, как создать и использовать макрос внутри файла одной рабочей книги. В случаи, когда необходимо использовать тот же макрос в других файлах рабочих книг, тогда можно сохранить его в личной книге макросов. У нее всегда одно название – Personal.xlsb. Она всегда открывается при запуске программы Excel, только скрыто. Данная книга не является доступной по умолчанию в Excel, поэтому ее нужно сначала подключить.

Как сохранить макрос в личную книгу макросов

Чтобы создать и схоронить код в личной книге макросов:

  1. Выберите инструмент: «РАЗРАБОТЧИК»-«Код»-«Запись макроса».
  2. В появившемся диалоговом окне «Запись макроса», из выпадающего списка «Сохранить в:» выберите опцию «Личная книга макросов». И нажмите на кнопку OK.
  3. Теперь выберите инструмент: «РАЗРАБОТЧИК»-«Код»-«Остановить запись».
  4. Откройте редактор Visual Basic: «РАЗРАБОТЧИК»-«Код»-«Visual Basic». Или нажмите комбинацию горячих клавиш ALT+F11. В окне «Project-VBAProject», в дереве проектов появиться доступная еще одна книга Personal.xlsb. Кликните на «плюсик» слева на против этой книги, чтобы раскрыть проект книги Personal.xlsb. А после двойным щелчком отройте ее Module1.
  5. В результате откроется окно кода модуля с зарегистрированным макросом. Удалите его код и введите код своего макроса. Выберите инструмент в редакторе макросов: «File»-«Save Personal.xlsb», а потом закройте редактор Visual Basic.

Теперь у вас подключена скрытая книга для хранения макросов, к которым можно получить доступ из любой другой рабочей книги. Личная книга макросов где находится находиться в папке автозагрузки файлов Excel – XLSTART: C:Documents and SettingsUser_NameAppDataRoamingMicrosoftExcelXLSTARTPersonal.xlsb

Примечание. XLSTART – это папка для автозагрузки файлов вместе с запуском программы Excel. Если сохранить файл в данную папку, то он будет открываться вместе с программой Excel. Для версий старше 2007 путь к папке автозагрузки будет следующим: C:Program FilesMicrosoft OfficeOffice12Xlstart.

Если вам нужно записать в нее новый макрос просто откройте редактор, а потом откройте модуль книги Personal.xlsb. Уже записанные в нее макросы удалять не нужно. Они не будут между собой конфликтовать если соблюдать одно простое правило – в одном модуле нельзя хранить макросы с одинаковыми именами.

Если вы еще не знакомы с макросами в Excel, то я вам даже немного завидую. Ощущение всемогущества и осознание того, что ваш Microsoft Excel можно прокачивать почти до бесконечности, которые придут к вам после знакомства с макросами — приятные чувства.

Однако, эта статья для тех, кто уже «познал мощь» и начал использовать макросы (чужие или написанные самостоятельно — не важно) в своей повседневной работе.

Макрос — это код (несколько строк) на языке Visual Basic, которые заставляют Excel сделать то, что вам нужно: обработать данные, сформировать отчет, скопипастить много однообразных таблиц и т.п. Вопрос — где эти несколько строк кода хранить? Ведь от того, где макрос хранится будет потом зависеть где он сможет (или не сможет) работать.

Если макрос решает небольшую локальную проблему в отдельно взятом файле (например обрабатывает внесенные в конкретный отчет данные особым образом), то логично хранить код внутри этого же файла. Без вопросов.

А если макрос должен быть относительно универсален и нужен в любой книге Excel — как, например, макрос для конвертирования формул в значения? Не копировать же его код на Visual Basic каждый раз в каждую книгу? Кроме того, рано или поздно, почти любой пользователь приходит к мысли, что неплохо было бы сложить все макросы в одну коробку, т.е. иметь их всегда под рукой. И может быть даже запускать не вручную, а сочетаниями клавиш? И вот тут может здорово помочь Личная Книга Макросов (Personal Macro Workbook).

Как создать Личную Книгу Макросов

На самом деле, Личная Книга Макросов (ЛКМ) — это обычный файл Excel в формате двоичной книги (Personal.xlsb), который автоматически в скрытом режиме открывается одновременно с Microsoft Excel. Т.е. когда вы просто запускаете Excel или открываете любой файл с диска, на самом деле открываются два файла — ваш и Personal.xlsb, но второго мы не видим. Таким образом все макросы, которые хранятся в ЛКМ оказываются доступы для запуска в любой момент, пока открыт Excel.

Если вы еще ни разу не пользовались ЛКМ, то изначально файл Personal.xlsb не существует. Самый легкий способ его создать — это записать рекордером какой-нибудь ненужный бессмысленный макрос, но указать в качестве места для его хранения Личную Книгу — тогда Excel будет вынужден автоматически ее для вас создать. Для этого:

  1. Откройте вкладку Разработчик (Developer). Если вкладки Разработчик не видно, то ее можно включить в настройках через Файл — Параметры — Настройка ленты (Home — Options — Customize the Ribbon).
  2. На вкладке Разработчик нажмите кнопку Запись макроса (Record Macro). В открывшемся окне выберите Личную книгу макросов (Personal Macro Workbook) как место для хранения записанного кода и нажмите OK:

    как сделать общий макрос excel для всей системы

  3. Остановите запись кнопкой Остановить запись (Stop Recording) на вкладке Разработчик (Developer)

Проверить результат можно, нажав на кнопку Visual Basic там же на вкладке Разработчик — в открывшемся окне редактора в левом верхнем углу на панели Project — VBA Project должен появиться наш файл PERSONAL.XLSB. Его ветку которого можно развернуть плюсиком слева, добравшись до Module1, где и хранится код только что записанного нами бессмысленного макроса:

как сделать общий макрос excel для всей системы

Поздравляю, вы только что создали себе Личную Книгу Макросов! Только не забудьте нажать на кнопку сохранения с дискеткой в левом верхнем углу на панели инструментов.

Как использовать Личную Книгу Макросов

Дальше все просто. Любой нужный вам макрос (т.е. кусок кода, начинающийся на Sub и заканчивающийся End Sub) можно смело копировать и вставлять либо в Module1, либо в отдельный модуль, добавив его предварительно через меню Insert — Module. Хранить все макросы в одном модуле или раскладывать по разным — исключительно вопрос вкуса. Выглядеть это должно примерно так:

как сделать общий макрос excel для всей системы

Запустить добавленный макрос можно в диалоговом окне, вызываемом с помощью кнопки Макросы (Macros) на вкладке Разработчик:

как сделать общий макрос excel для всей системы

В этом же окне, нажав кнопку Параметры (Options), можно задать сочетание клавиш для быстрого запуска макроса с клавиатуры. Будьте внимательны: сочетания клавиш для макросов различают раскладку (русская или английская) и регистр.

Кроме обычных макросов-процедур в Личной Книге можно хранить и пользовательские макро-функции (UDF = User Defined Function). В отличие от процедур, код функций начинаются с оператора Function или Public Function, а заканчиваются на End Function:

как сделать общий макрос excel для всей системы

Код необходимо аналогичным образом скопировать в любой модуль книги PERSONAL.XLSB и затем можно будет вызвать функцию обычным образом, как любую стандарную функцию Excel, нажав кнопку fx в строке формул и выбрав функцию в окне Мастера Функций в категории Определенные пользователем (User Defined):

как сделать общий макрос excel для всей системы

Примеры таких функций можно в больших количествах найти в интернете или здесь же на сайте (сумма прописью, приблизительный текстовый поиск, ВПР 2.0, конвертация кириллицы в транслит и т.п.)

Где хранится Личная Книга Макросов

Если вы будете использовать Личную Книгу Макросов, то рано или поздно у вас возникнет желание:

  • поделиться своими накопленными макросами с другими пользователями
  • скопировать и перенести Личную Книгу на другой компьютер
  • сделать ее резервную копию

Для этого нужно будет найти файл PERSONAL.XLSB на диске вашего компьютера. По умолчанию, этот файл хранится в специальной папке автозапуска Excel, которая называется XLSTART. Так что все, что нужно — это добраться до этой папки на нашем ПК. И вот тут возникает небольшая сложность, потому что местоположение этой папки зависит от версии Windows и Office и может различаться. Обычно это один из следующих вариантов:

  • C:Program FilesMicrosoft OfficeOffice12XLSTART
  • C:Documents and SettingsComputerApplication DataMicrosoftExcelXLSTART
  • C:Usersимя-вашей-учетной-записиAppDataRoamingMicrosoftExcelXLSTART

Как вариант, можно спросить о положении этой папки сам Excel с помощью VBA. Для этого в редакторе Visual Basic (кнопка Visual Basic на вкладке Разработчик) нужно открыть окно Immediate сочетанием клавиш Ctrl+G, ввести туда команду ? Application.StartupPath и нажать на Enter:

как сделать общий макрос excel для всей системы

Полученный путь можно скопировать и вставить в верхнюю строку окна Проводника в Windows и нажать Enter — и мы увидим папку с нашим файлом Личной Книги Макросов:

как сделать общий макрос excel для всей системы

P.S.

И несколько практических нюансов вдогон:

  • при использовании Личной Книги Макросов Excel будет запускаться чуть медленнее, особенно на слабых ПК
  • стоит периодически очищать Личную Книгу от информационного мусора, старых и ненужных макросов и т.п.
  • у корпоративных пользователей бывают иногда сложности с использованием Личной Книги, т.к. это файл в системной скрытой папке

Ссылки по теме

  • Что такое макросы, как их использовать в работе
  • Полезности для VBA-программиста
  • Тренинг «Программирование макросов на VBA в Microsoft Excel»

In Excel, you can make it so all of your macros can be easily accessed by any Excel workbook.

To do this we need to create what is called a «personal macro workbook» and then save it.  All of the macros that we want to use in Excel will be stored within this personal macro workbook and will then be accessible by any Excel file.

Steps to Make any Macro Available in All Excel Files

  1. Open an Excel file and then go to record a dummy macro, recording this dummy macro is what will create the «personal macro workbook» that we need in order to store the macros.
  2. To record a macro go to the Developer tab, if that is visible, or simply look to the bottom left of the Excel window.  From there, click the Record Macro button:
    0090ff8f1346bb6e5fd58a4f23a2e878.jpg
  3. On the screen that appears, make sure to select Personal Macro Workbook from the Store macro in: drop down box and then hit the OK button. Nothing else matters here because we just need to record a simple macro, anything really.
    aa5c83eef649501987c1791017105057.png
  4. Select any cell in the worksheet and then just click the Stop Recording macro button, which is in the exact same location as the Record Macro button in step 2.
    4f55b8f6ab9215a22b4f2630cbcf1a80.png
  5. Now hit Alt + F11 on the keyboard so we can go to the VBA/Macro editor window.  You will now see the PERSONAL.XLSB file appear in the top left pane of the window.
    122bce41fec5716168a2e10c8736d184.png
  6. All you have to do now is to add Modules and Macros to this file like you would to any normal Excel file. Double-click Module 1 and we see the macro that we just recorded:
    80a7034fa3c5d613c06bc0f72c54f20c.png

As you can see, this new PERSONAL.XLSB file behaves just like a regular file in the VBA window.  This is where you will store any macros that you want to be able to access from all Excel files.

Notes

The personal macro workbook file does NOT travel with your Excel files when you send them; this PERSONAL.XLSB file only remains on your computer for you to use.  So, if you send a workbook to another person, they will not be able to access the same macros that you have unless you also put those macros in the workbook you sent.

You must follow the above steps to create the personal macro workbook but, once you have created it, you can access it from any workbook on your computer by simply going to the VBA/Macro editor window (Alt + F11).  As such, once it is created, adding macros to this new file is the same as adding it to any other Excel file — open any workbook, go to the VBA window, add a module to the PERSONAL.XLSB file and then add a macro.

The sample file for this tutorial is empty because, remember, you cannot send the personal macro workbook file with Excel files.


Excel VBA Course

Excel VBA Course — From Beginner to Expert

200+ Video Lessons
50+ Hours of Instruction
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Similar Content on TeachExcel

Vlookup Function That Searches The Entire Workbook in Excel — UDF

Macro: With this VLOOKUPWORKBOOK function, you will have to power to more quickly and easily ana…

Copy and Paste Data using Macro VBA in Excel

Tutorial: How to copy and paste data using a Macro in Excel. I’ll show you multiple ways to do this,…

Get the Name of a Worksheet in Macros VBA in Excel

Tutorial: How to get the name of a worksheet in Excel using VBA and Macros and also how to store tha…

Highlight, Sort, and Group the Top and Bottom Performers in a List in Excel

Tutorial:
How to highlight the rows of the top and bottom performers in a list of data.
This allows…

Sort Data that Doesn’t Have Headers in Ascending Order in Excel

Macro: Sort data that doesn’t have headers in ascending order in Excel with this macro. This is a…

Loop through a Range of Cells in a UDF in Excel

Tutorial:
How to loop through a range of cells in a UDF, User Defined Function, in Excel. This is …

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Excel VBA Course

Excel VBA Course — From Beginner to Expert

200+ Video Lessons

50+ Hours of Video

200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Make excel available for all workbooks

One of the best features of Ms Excel is Macros. In our earlier blog we have shown how to write excel macro to compute liner interpolation, and now we will see how to make a macro available in all workbook.

Excel Macro is only available in the workbook on which we created it. However, with the following method you can make it available for all the workbooks/excel files.

  1. Open Visual Basic Editor by navigating Developer Tab > Visual Basic
  2. Create Module by going to Insert Tab > Module
  3. Write the desired function/macro that you need to make it available for all excel workbook/files
  4. Save the current workbook with “.xlam” extension (say “LinearInterpolation Function.xlam”) in the default directory which windows prompts while saving.
  5. Go to Files > Options > Add-in and select the above Excel file/Macro from the list of Inactive Application Add-ins & Click Go. This step makes the function/macro available for all workbook.

Activating excel macro/add-ins to make macro available for each workbook

Activate excel macro/add-ins to make macro available for each workbook

Related Posts

Понравилась статья? Поделить с друзьями:
  • Macros codes for excel
  • Macros are enabled excel
  • Macroeconomics the word macroeconomics means economics in the large
  • Macro with excel and word
  • Macro run macro excel vba