Глобальный макрос для excel

I have a macro I want to have automatically available to all Excel worksheets. So I have placed the file AutoTagExcelMacro.xla in the folder C:Program Files (x86)Microsoft OfficerootOffice16XLSTART. And that seems to do the trick.

I’ve been told by Microsoft support that I then, after installing the file there, need to call RunAutoMacros on the installed file. Do I? And what does it do in this case? There is no Open or Activate macro in the macro.

Is this a way of registering it with Excel as something to always run? As I said, installing the file without running RunAutoMacros does make the macro available in all worksheets on our test systems. But all of our test systems have called RunAutoMacros in the past, so that past call may make a difference.

After copying the file to XLSTART, when I create a new workbook the macro is there in it. I did nothing but create a new workbook to get this:

enter image description here

Глобальный макрос для всего Excel

The_Immortal

Дата: Вторник, 17.06.2014, 15:57 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 24


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Всех приветствую!

Не знаю как правильно сформулировать задачу, поэтому опишу как могу. Есть макрос, запуск которого нужно реализовать для любого excel-документа, т.е. встроить в сам офис.

Подскажите, пожалуйста, каким образом это можно сделать, в какую сторону копать?

Спасибо!

 

Ответить

RAN

Дата: Вторник, 17.06.2014, 16:09 |
Сообщение № 2

Группа: Друзья

Ранг: Экселист

Сообщений: 5645

вариантов 3
1. обратиться в майкрософт, чтобы они встроили ваш макрос в офис.
2. поместить макрос в личную книгу макросов (personal)
3. поместить макрос в надстройку


Быть или не быть, вот в чем загвоздка!

 

Ответить

Alex_ST

Дата: Вторник, 17.06.2014, 16:27 |
Сообщение № 3

Группа: Друзья

Ранг: Участник клуба

Сообщений: 3176


Репутация:

604

±

Замечаний:
0% ±


2003

Ну, вообще-то, Андрей, конечно, прав…
Каков вопрос, таков и ответ — в общем виде.
Вот если Вы потрудитесь и откроете тайну, что должен этот макрос делать и по каким событиям, то ответ можете получить и более подробный.
Если нет, то смотрите в «Готовых решениях». Там есть несколько примеров надстроек.



С уважением,
Алексей
MS Excel 2003 — the best!!!

 

Ответить

DrugON

Дата: Среда, 21.01.2015, 10:58 |
Сообщение № 4

Группа: Пользователи

Ранг: Прохожий

Сообщений: 3


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Ребят, та же проблема.
Раньше была личная книга макросов, которой постоянно пользовался. Но в последних версиях Экселя её нет. Куда сохранять модуль — непонятно.
[moder]Неее, это другая проблема. А даже если и та, то в любом случае Вам нужно создать свою тему, так в Правилах форума написано.
Эта тема закрыта.


Видно птицу по помёту

 

Ответить

Глобальная переменная в проекте VBA Excel. Объявление глобальной переменной в модуле проекта VBA и обращение к ней из других модулей того же проекта.

Объявление глобальной переменной

Глобальная переменная — это переменная, которая объявлена в одном из модулей проекта VBA и доступна для использования во всех остальных модулях.

Чтобы переменная стала глобальной, она должна быть объявлена в начале модуля перед первой процедурой (раздел Declarations) с помощью оператора Public. Этот способ работает во всех модулях проекта VBA Excel.

Допускается объявление глобальной переменной с помощью оператора Global, но такой способ считается устаревшим и на сайте разработчиков уже не упоминается. Объявить глобальную переменную с оператором Global можно только в стандартном модуле.

Пример объявления глобальных переменных в любом модуле проекта VBA:

Public myGlobVar1 ‘по умолчанию — As Variant

Public myGlobVar2 As String

Public myGlobVar3 As Double

Объявление глобальных переменных

Объявление глобальных переменных

Обращение к глобальной переменной

Примеры обращения к глобальной переменной, объявленной в разных типах модулей проекта VBA Excel. Актуально для обращения из модуля любого типа данного проекта.

Переменная в стандартном модуле

Если глобальная переменная (myGlobVar) объявлена в стандартном модуле (Module1) с уникальным именем, не повторяющимся в других модулях, к ней можно обращаться из других модулей по одному имени (в примере — из модуля формы):

Private Sub CommandButton1_Click()

    myGlobVar = «Глобальная переменная»

    TextBox1.Text = myGlobVar

End Sub

Стандартное обращение с указанием имени модуля (Module1), в котором объявлена глобальная переменная (myGlobVar):

Private Sub CommandButton1_Click()

    Module1.myGlobVar = «Глобальная переменная»

    TextBox1.Text = Module1.myGlobVar

End Sub

Переменная в модуле книги

Глобальная переменная (myGlobVar), объявленная в модуле книги, доступна при обращении к ней из других модулей с помощью следующего кода VBA Excel:

Sub Primer1()

    ThisWorkbook.myGlobVar = «Глобальная переменная»

    MsgBox ThisWorkbook.myGlobVar

End Sub

Переменная в модуле листа

Обращение к глобальной переменной (myGlobVar), объявленной в модуле рабочего листа (Лист1), из других модулей по имени листа (в проводнике проекта находится без скобок слева от имени ярлыка):

Sub Primer2()

    Лист1.myGlobVar = «Глобальная переменная»

    MsgBox Лист1.myGlobVar

End Sub

По имени ярлыка (в проводнике проекта находится в полукруглых скобках справа от имени листа):

Sub Primer3()

    Worksheets(«Лист1»).myGlobVar = «Глобальная переменная»

    MsgBox Worksheets(«Лист1»).myGlobVar

End Sub

Переменная в модуле формы

Глобальная переменная (myGlobVar), объявленная в модуле формы (UserForm1), доступна при обращении к ней из других модулей с помощью следующего кода VBA Excel:

Sub Primer4()

    UserForm1.myGlobVar = «Глобальная переменная»

    MsgBox UserForm1.myGlobVar

End Sub

Переменная в личной книге макросов

Обращение к глобальной переменной (myGlobVar), объявленной в модуле ЭтаКнига проекта VBAProject (PERSONAL.XLSB) из модуля проекта VBA обычной книги Excel:

Sub Primer5()

    Workbooks(«PERSONAL.XLSB»).myGlobVar = «Глобальная переменная»

    MsgBox Workbooks(«PERSONAL.XLSB»).myGlobVar

End Sub

Мне не удалось получить доступ из проекта VBA текущей книги Excel к глобальной переменной, объявленной в стандартном модуле личной книги макросов.


» @ProfoundlyOblivious Could you please post an answer telling us how to do each part best — digitally signing, trusted location, etc. and what/where we should tell people to look for macros being disabled? – David Thielen «

Disclosure: I am not an expert in software deployment, my knowledge is limited to the obstacles I encountered sharing my VBA solutions among peers on IT managed networks.

Note: The dialog boxes in your post do not all originate from the same cause. The first relates to security and the others to file availability.


Security

Macros have been, and still are, used in the development and circulating of malicious software. As a result macros are disabled by default and require user interaction to run.

  • Macro Security Settings
    Macros are enabled through the Trust Center, which is accessed through the file menu. These settings are independent for each Office application and some applications may have additional options involving the suppression of a dialog box. Such as Excel where all macros may be disaabled without notification or all macros may be disaabled with notification. There are three basic settings for all Office applications summarized as:

    • Disable all macros
    • Disable all unsigned macros
    • Enable all macros (Not Recommended)

    I strongly recommend that one does not enable all macros. It may achieve a desired result but I believe the risk is far too great to warrant the consideration.

  • Digitally Signed Macros
    A digitally signed macro in and of itself simply means the underlying code has not been changed by anyone since last saved by the signer. If the signer’s certificate is installed on a computer as a trusted publisher then macros signed with that certificate can run without notification under the requisite macro security setting.

    • In corporate environments, IT may retain a library of certificates and there may be an established procedure for an internal developer to submit a project for wider circulation, whereafter IT signs the project so it can be run with minimal intervention.
    • In my experience however, I have found many companies do not have an SOP for this process or that the process is prohibitively onerous. At such times, I turn to self-signed certificates. A self-signed certificate if miraculous for personal development because it provides ample flexibility without incurring the risk if allowing unsigned code to run. The problem, of course, then comes with sharing your code because the recipient will not have your certificate installed. They could install my certificate but my personal preference is that I send an unsigned project and they create a certificate and sign the project themselves. This is an easy step-by-step process that requires no skill beyond the ability to follow instructions.
  • Trusted Location
    A document saved in a trusted location can run macros without notifications. Trusted locations are added in the Trust Center.

    By default, XLStart is a trusted location


File Availability

When Excel is opened, it will try to refresh links to other data sources and add-ins. Those files must be open for a successful refresh and a dialog box will appear if the refresh fails.

Based on little more than experience and deduction, I believe this message is often semi-erroneous and driven by either the lack of a time out timer or too short of one. I have tested this with a simple worksheet and a simple add-in. The message pops saying the link could not be updated but it was open and updated by the time I manually check the status of the connection.

In other words, the dialog box was an iritation that served no value.

There is an option that suposedly offers some control over the «Links Could Not Be Updated» window with options along the lines of:

  • Update links and notify
  • Update links and do not notify

I have found these settings unreliable and prone to resets from crashes and updates.

To the best of my knowledge, the most assured way if avoiding this type of warning is to install the add-in after Excel is stable and uninstall the add-in before Excel closes. Of course this comes with it’s on set of problems including a user perceivable slower loading time.

  • Remove From My Forums
  • Question

  • Hello,

    how is the right way.

    I have a function.

    Target:

     To open a Excel Sheet, make a menue button.

     If I press the button the check for actual sheet is necessary.

    At moment it is only works with the sheet where the macro is.

    How I can make it global? Where is the right place?

    Sub MakroCheckCodes()
        Dim i As Integer
        Dim iVorgaenger As Integer
        
        Dim valueAktuell As Long
        Dim valueVorgaenger As Long
        
        ThisWorkbook.Sheets(1).Activate
        
        For i = 2 To 50
          Cells(i, 1).NumberFormat = "0"
          iVorgaenger = i - 1
          valueAktuell = CLng(Cells(i, 1))
          valueVorgaenger = Cells(iVorgaenger, 1)
          If valueAktuell = (valueVorgaenger + 1) Or valueAktuell = valueVorgaenger Then
          Cells(i, 2).FormulaR1C1 = "'=IO"
          Cells(i, 2).Interior.ColorIndex = 35 'grün
            ' With Selection.Interior
            '    .ColorIndex = 6
            '    .Pattern = xlSolid
            ' End With
          Else
             Cells(i, 2).FormulaR1C1 = "'=NIO"
             Cells(i, 2).Interior.ColorIndex = 3 'rot
            ' With Selection.Interior
             '   .ColorIndex = 38
             '   .Pattern = xlSolid
             'End With
          End If
        Next i
    End Sub

    Menue for all sheets

    • Edited by

      Tuesday, July 24, 2012 11:17 AM
      Format

Answers

  • The best place for a global is your personal macro workbook (persönliche Makroarbeitsmappe) Personal.xlsb. If you don’t have one, start by recording a small macro and specify that it must be available in all workbooks. This will create Personal.xlsb.

    Once it exists, you can edit it by activating the Visual Basic Editor.

    Copy your macro into a module in Personal.xlsb.

    To make it applicable to the active sheet, regardless of the workbook it is in, remove the line

    ThisWorkbook.Sheets(1).Activate


    Regards, Hans Vogelaar

    • Proposed as answer by
      VBAToolsMVP, Editor
      Tuesday, July 24, 2012 11:45 AM
    • Marked as answer by
      Andreas Bauer2
      Tuesday, July 24, 2012 1:07 PM

  • With the removal of ThisWorkbook.Sheets(1).Activate, the macro will operate on the currently active worksheet in the currently active workbook.

    If you want it to operate on the first worksheet in the currently active workbook, insert the following line:

        Worksheets(1).Select


    Regards, Hans Vogelaar

    • Marked as answer by
      Andreas Bauer2
      Tuesday, July 24, 2012 2:00 PM

  • you can using:

    dim wkb as workboook
    set wkb = Workbooks(ActiveWorkbook.name)
    
    Dim wks As Worksheet
    set wks = wkb.sheet("Sheet1") 'or another
    
    'or loop 
    'For Each wks In wkb.Worksheets
    ' if wks.name = "ala ma kota" then ...
    'next

    also I can recommend you my simple Add-in to step threw workbooks/worksheet

    Move between worksheets active workbook Add-in


    Oskar Shon, Office System
    MVP

    Press if Helpful; Answer when a problem solved

    • Edited by
      VBAToolsMVP, Editor
      Tuesday, July 24, 2012 1:51 PM
    • Marked as answer by
      Andreas Bauer2
      Tuesday, July 24, 2012 2:00 PM

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

В начале модуля

Visual Basic
1
Public IFEMPTY As Variant

При кучи условий в другом модуле

Visual Basic
1
IFEMPTY = 9

Так вот, в самом начале макроса, первым делом прописал:

Visual Basic
1
MsgBox IFEMPTY

Так вот, если я запускаю макрос без условия тригера

Visual Basic
1
IFEMPTY = 9

При следующем запуске макроса пишет, что переменная ничему не ровна

Но стоит затригерить и присвоить

Visual Basic
1
IFEMPTY = 9

При прожатии макроса с самого начала пишет, что

Visual Basic
1
IFEMPTY = 9

То есть он у него в памяти остался таким, ведь никаких действий вообще не было предпринято для тригера

Это что же получается, нужно постоянно в конце макроса присваивать переменным нулевые значения?
А если у меня таких глобальных переменных 70?!

Или мне необходимо объявлять в модуле переменные, как static?
Я просто не могу сейчас проверить

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

Excel для Microsoft 365 Excel для Microsoft 365 для Mac Excel 2021 Excel 2021 для Mac Excel 2019 Excel 2019 для Mac Excel 2016 Excel 2016 для Mac Excel 2013 Excel 2010 Excel 2007 Еще…Меньше

Когда вы впервые создаете макрос в книге, он работает только в ней. А если вам нужно использовать макрос в других книгах? Чтобы макросы были доступны при каждом запуске Excel, создайте их в книге с именем Personal.xlsb. Это скрытая книга, которая хранится на компьютере и открывается в фоновом режиме при каждом Excel.

Макросы и средства VBA находятся на вкладке Разработчик, которая по умолчанию скрыта, поэтому сначала нужно включить ее. Дополнительные сведения см. в статье Отображение вкладки «Разработчик».

Вкладка "Разработчик" на ленте

Теперь создайте макрос. Мы зафиксим макрос, который ничего не делает, но создаст личную книгу макроса.

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

  1. Перейдите на вкладку Разработчик и нажмите кнопку Запись макроса.

    Группа "Код" на вкладке "Разработчик"

  2. В диалоговом окне Запись макроса не помешает ввести имя макроса в поле Имя макроса. Вы можете принять имя, которое Excel, например Макрос1, так как это просто временный макрос.

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

  3. В поле Сохранить в выберитеЛичная книга макроса и > ОК. Это самый важный шаг, так как если у вас еще нет личной книги макроса, Excel создаст ее.

  4. Щелкните Разработчик > Остановитьзапись , Excel создайте личную книгу макроса.

  5. При закрытии книги вам будет предложено сохранить как книгу, так и личную книгу макроса.

Чтобы увидеть созданный макрос:

  1. Перейдите в >Visual Basic, чтобы запустить редактор Visual Basic (VBE),в котором хранятся макросы.

  2. Книгу «Личные макросы» можно найти в области Project проводника слева. Если вы не видите его, перейдите в > Project проводник.

  3. Дважды щелкните папку VBA Project (PERSONAL.xlsb) > Modules > Module1, и вы увидите пустой записанный макрос1. Вы можете удалить его или оставить, чтобы добавить код к более поздней.

    Примечание: При записи макроса в новом экземпляре Excel VBA автоматически создает новую папку Module и ее номер прибавления. Поэтому если у вас уже есть Module1 и Module2, VBA создаст Модуль3. Модули можно переименовать в окне Свойства под обозревателем Project ,чтобы они лучше отражали то, что делают макрос внутри них.

Перемещение макросов на другой компьютер

Файл Personal.xlsB хранится в папке XLSTART. Если вы хотите поделиться макросами с другими, вы можете скопировать их в папку XLSTART на других компьютерах или скопировать некоторые или все макрос в файл Personal.xlsb на других компьютерах. Вы можете найти XLSTART в Windows проводнике.

Если вы хотите поделиться одним или несколькими макросами с другими людьми, вы можете отправить им книгу, содержаную их. Можно также предоставить доступ к книге на общем сетевом диске или в библиотеке служб SharePoint Services.

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

Убедитесь, что на ленте отображается вкладка Разработчик. По умолчанию вкладка Разработчик не отображается, поэтому сделайте следующее:

  1. Перейдите в Excel > параметры…> ленты & панель инструментов.

  2. В категории Настроить ленту в списке Основные вкладки установите флажок Разработчик, а затем нажмите кнопку Сохранить.

Теперь создайте макрос. Мы зафиксим макрос, который ничего не делает, но создаст личную книгу макроса.

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

  1. Перейдите на вкладку Разработчик и нажмите кнопку Запись макроса.

  2. В диалоговом окне Запись макроса не помешает ввести имя макроса в поле Имя макроса. Вы можете принять имя, которое Excel, например Макрос1, так как это просто временный макрос.

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

  3. В поле Сохранить в выберитеЛичная книга макроса и > ОК. Это самый важный шаг, так как если у вас еще нет личной книги макроса, Excel создаст ее.

  4. Щелкните Разработчик > Остановитьзапись , Excel создайте личную книгу макроса.

  5. При закрытии книги вам будет предложено сохранить как книгу, так и личную книгу макроса.

Чтобы увидеть созданный макрос:

  1. Нажмите кнопку > Visual Basic, чтобы запустить редактор Visual Basic (VBE),в котором хранятся макросы.

  2. Книгу «Личные макросы» можно найти в области Project проводника слева. Если вы не видите его, перейдите в > Project проводник.

  3. Дважды щелкните папку VBA Project (PERSONAL.xlsb) > Modules > Module1, и вы увидите пустой записанный макрос1. Вы можете удалить его или оставить, чтобы добавить код к более поздней.

Примечание: При записи макроса в новом экземпляре Excel VBA автоматически создает новую папку Module и ее номер прибавления. Поэтому если у вас уже есть Module1 и Module2, VBA создаст Модуль3. Модули можно переименовать в окне Свойства под обозревателем Project ,чтобы они лучше отражали то, что делают макрос внутри них.

Перемещение макросов на другой компьютер

Файл Personal.xlsB хранится в папке запуска системы. Если вы хотите поделиться макросами с другими, можно скопировать Personal.xlsb в папку запуска на других компьютерах или скопировать некоторые или все макрос макроса в файл Personal.xlsb на других компьютерах. В Finder выберите Перейти, а затем, удерживая клавишу OPTION, выберите Библиотека. В области Библиотека перейдите к группе Containers > xyz.Office (где xyz — это текстовая строка, например «UBF8T346G9») > User Content > Startup > Excel. В Personal.xlsb в Excel папку.

Если вы хотите поделиться одним или несколькими макросами с другими людьми, вы можете отправить им книгу, содержаную их. Можно также предоставить доступ к книге на общем сетевом диске или в библиотеке служб SharePoint Services.

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

Дополнительные сведения

Вы всегда можете задать вопрос специалисту Excel Tech Community или попросить помощи в сообществе Answers community.

Нужна дополнительная помощь?

Понравилась статья? Поделить с друзьями:
  • Годовой отчет в формате excel
  • Глобальные процедуры excel vba
  • Годовой отчет excel скачать
  • Гликемический индекс продуктов полная таблица скачать excel
  • Годовой личный бюджет в excel