Disable macros excel vba

Excel for Microsoft 365 Word for Microsoft 365 Outlook for Microsoft 365 PowerPoint for Microsoft 365 Access for Microsoft 365 Excel 2021 Word 2021 Outlook 2021 PowerPoint 2021 Access 2021 Visio Professional 2021 Visio Standard 2021 Excel 2019 Word 2019 Outlook 2019 PowerPoint 2019 Access 2019 Visio Professional 2019 Visio Standard 2019 Excel 2016 Word 2016 Outlook 2016 PowerPoint 2016 Access 2016 Visio Professional 2016 Visio Standard 2016 Excel 2013 Word 2013 Outlook 2013 PowerPoint 2013 Access 2013 Visio Professional 2013 Visio 2013 Excel 2010 Word 2010 Outlook 2010 PowerPoint 2010 Access 2010 Visio Premium 2010 Visio 2010 Visio Standard 2010 Excel Starter 2010 More…Less

A macro is a series of commands used to automate a repeated task and can be run when you have to perform the task. Macros can automate frequently used tasks to save time on keystrokes and mouse actions.

However, some macros can pose a security risk. Macros are often used by people with malicious intent to quietly install malware, such as a virus, on your computer or into your organization’s network.

Warning: Never enable macros in a Microsoft 365 file unless you’re sure what those macros do. Unexpected macros can pose a significant security risk. You don’t have to enable macros to see or edit the file; only if you want the functionality provided by the macro. For more information see Protect yourself from macro viruses.

Change macro settings in the Trust Center

Macro settings are located in the Trust Center. However, if your device is managed by your work or school the system administrator might prevent anyone from changing settings.

Important: When you change your macro settings in the Trust Center, they are changed only for the Microsoft 365 program that you are currently using. The macro settings are not changed for all your Microsoft 365 programs.

  1. Click the File tab.

  2. Click Options.

  3. Click Trust Center, and then click Trust Center Settings.

  4. In the Trust Center, click Macro Settings.

    macro settings area of trust center

  5. Make the selections that you want, then click OK.

Note: The options are slightly different in Excel, we’ll call those out as we go.

  • Disable all macros without notification     Macros and security alerts about macros are disabled.

    In Excel this option is Disable VBA macros without notification and it only applies to VBA macros.

  • Disable all macros with notification     Macros are disabled, but security alerts appear if there are macros present. Enable macros on a case-by-case basis.

    In Excel this option is Disable VBA macros with notification and it only applies to VBA macros.

  • Disable all macros except digitally signed macros     Macros are disabled, and security alerts appear if there are unsigned macros present. However, if the macro is digitally signed by a trusted publisher, the macro just runs. If the macro is signed by a publisher you haven’t trusted yet, you are given the opportunity to enable the signed macro and trust the publisher.

    In Excel this option is Disable VBA macros except digitally signed macros and it only applies to VBA macros.

  • Enable all macros (not recommended, potentially dangerous code can run)     All macros run without confirmation. This setting makes your computer vulnerable to malicious code.

    In Excel this option is Enable VBA macros (not recommended, potentially dangerous code can run) and it only applies to VBA macros.

  • Excel also has a checkbox for Enable Excel 4.0 macros when VBA macros are enabled. If you select this checkbox all of the above settings for VBA macros will also apply to Excel 4.0 (XLM) macros.

    If this checkbox is not selected XLM macros are disabled without notification.

  • Trust access to the VBA project object model     Disallow or allow programmatic access to the Visual Basic for Applications (VBA) object model from an automation client. This security option is for code written to automate a Microsoft 365 program and manipulate the VBA environment and object model. It is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code. For automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box.

    Note: Microsoft Publisher and Microsoft Access have no Trust access to the VBA project model object option.

For info on creating macros please see Quick start: Create a macro.

For info on using macros on a machine running Windows S see Block suspicious macros in Office on Windows 10 S.

See Also

Change macro security settings in Excel

How malware can infect your PC

Need more help?

I would like to test an Excel VBA app I made.
However the VBA code messes around with the visibility of cells and that’s a pest when editing the sheet.

Is there an option is enable and disable macro’s on the fly without having to

Close the sheet
Change the macro settings
Reopen the sheet
Close the sheet
Change the macro settings.
etc.

ashleedawg's user avatar

ashleedawg

20k8 gold badges73 silver badges104 bronze badges

asked Sep 28, 2011 at 7:44

Johan's user avatar

0

As far as I know, you can’t enable / disable macros from an opened workbook on the fly.
Yet, you shouldn’t have to because macros are only triggered thanks to a user click.

The only case I would see is for the Event Procedures (Worksheet_Change or else).
You could then create procedures to activate / deactivate events and call them from buttons in your worksbook:

Sub enableEvents()
    Application.EnableEvents = True
End Sub

Sub disableEvents()
    Application.EnableEvents = False
End Sub

You can also try these tips from Chris Pearson website using global vars you would change depending on your needs:

Public AbortChangeEvent As Boolean

And check if afterwards:

Private Sub Worksheet_Change(ByVal Target As Range)
    If AbortChangeEvent = True Then
        Exit Sub
    End If
    '
    ' rest of code here
    '
End Sub

Community's user avatar

answered Sep 28, 2011 at 7:56

JMax's user avatar

JMaxJMax

25.9k12 gold badges69 silver badges88 bronze badges

1

To disable macros on the fly, use «Application.EnableEvents = False» via the Immediate window in the VBA editor (and «Application.EnableEvents = True» to turn them back on).

answered Mar 6, 2015 at 14:32

T.J.L.'s user avatar

T.J.L.T.J.L.

1752 silver badges9 bronze badges

4

You can also hold down SHIFT when you open a document to disable macros.

Blue's user avatar

Blue

22.4k7 gold badges59 silver badges90 bronze badges

answered Aug 10, 2016 at 7:51

JohannesGbg's user avatar

3

As of Excel 2010* there’s actually an option on the «Developer» tab which allows you to disable macros as easy as ABC. Design Mode lets you do just that!

*Maybe even earlier versions.

answered Nov 12, 2015 at 23:19

Panos Gr's user avatar

Panos GrPanos Gr

6675 silver badges13 bronze badges

2

I often fire Macros when opening a workbook but sometimes I don’t want the Macro to fire so I can work on the code. So what I put a Macro in a separate workbook that does the following:

  1. Disables macros
  2. Opens the workbook in question
  3. Enables macros
  4. Then closes the original workbook
  5. Leaves the second workbook open
    Here’s the code:
Sub OpenClose()

    'Opens Workbook below with Macors disabled

    'After it is open Macros are enabled

    'This Workbook then closes without saving changes, leaving only the workbook below open

    '************************************************************
    'User only needs to change the workbook name on the next line
    WorkbookToOpenNoMacros = "Gaby.xlsm"
    '************************************************************

    Dim wb As Workbook

    Set wb = Application.ThisWorkbook

    Application.EnableEvents = False

    Application.Workbooks.Open (ActiveWorkbook.Path & "" & WorkbookToOpenNoMacros)

    Application.EnableEvents = True

    wb.Saved = True

    wb.Close SaveChanges:=False

End Sub

fcdt's user avatar

fcdt

2,3315 gold badges12 silver badges26 bronze badges

answered Aug 16, 2020 at 2:15

Kellog's user avatar

I have Office 2013 and I found a button on the VBA window that did this for me very easily.

There’s a play, pause and stop button on the toolbar. In Excel, they are actually called, Run Macro, Break and Reset.

Click the Break button (pause) and any running macros should stop running. I only tested it on one macro but seems reasonable to presume that this will work in general.

Also, I believe those buttons were there for many versions of Excel, so it’s worth checking earlier versions.

answered Oct 5, 2016 at 14:27

Shannon C's user avatar

1

A macro is a set of commands that you can use to automate a repetitive task and run whenever you need to. This article discusses the risks associated with working with macros, as well as how to enable or disable macros in the Trust Center. Using macros in Excel reduces human error and saves time by automating repetitive tasks.

Macro security in Excel

Before you enable macros in your worksheets, you should understand how dangerous they can be.

Though VBA (Visual Basic for Applications) codes are extremely effective at automating complex and repetitive tasks, they pose a significant security risk. Unintentionally running a malicious macro can damage or completely delete files on your hard drive, corrupt your data, and even corrupt your Microsoft Office installation. As a result, the default setting in Excel is to disable all macros with notification.

How can these dangers be avoided? Simply follow one simple rule: enable only safe macros – those you’ve written or recorded yourself, macros from reliable sources, and VBA codes you’ve thoroughly reviewed and comprehended.

How to Enable macros for individual workbooks?

Macros can be enabled for a specific file in two ways: directly from the workbook and via the Backstage view.

1. Enable macros directly via security notice:

When you first open a workbook containing macros with the default macro settings, the yellow security warning bar appears at the top of the sheet, right under the ribbon:

The Microsoft Excel Security Notice will be displayed if the Visual Basic Editor is open at the time you open the file with macros:

If you are confident in the file’s origin and that all macros are safe, click the Enable Content or Enable Macros button. This activates the macros and marks the file as a trusted document. 

2. Turn on macros in Backstage view:

The Office Backstage view is another way to enable macros for a specific workbook. Here’s how to do it:

  • Click the File tab, then Info from the left menu.
  • Click Enable Content > Enable All Content, in the Security Warning area.

Your workbook, like the previous method, will become a trusted document.

How to Enable macros for one session?

In some cases, enabling macros for a single instance makes sense. For example, suppose you received an Excel file containing VBA code that you want to investigate but do not want to make it a trusted document.

The steps below will walk you through the process of enabling macros for the duration of the file’s open state:

  1. Navigate to the File tab > Info.
  2. Click Enable Content > Advanced Options in the Security Warning area.
  3. Select Enable content for this session in the Microsoft Office Security Options dialogue box, then click OK.

This enables macros for a single-use. The warning will reappear if you close and then reopen the workbook.

How to Enable macros in all workbooks through the Trust Center?

Microsoft Excel decides whether to allow or disallow VBA code execution based on the macro setting selected in the Trust Center, which is where you configure all of Excel’s security settings.

To enable macros by default in all Excel workbooks, follow these steps:

  • Navigate to the File tab and then to Options.
  • Select Trust Center from the left-hand pane and then click on Trust center setting.

  • In the Trust Center dialog box, click Macro Settings on the left, select Enable all macros and click OK.

Notes: The option you select in the Trust Center becomes the new default macro setting for all of your Excel files. Instead, if you only want to enable macros for specific workbooks, save them in a trusted location.

How to Enable macros permanently in a trusted location?

Rather than tampering with the global macro settings, you can instruct Excel to trust specific locations on your computer or local network.

Follow these steps to view the current trusted locations or to add a new one:

  • Navigate to File > Options.
  • Select Trust Center from the left-hand pane, and then click Trust Center Settings.
  • On the left side of the Trust Center dialogue box, select Trusted Locations. You will be presented with a list of the default trusted locations. These locations are critical for the proper operation of Excel add-ins, macros, and templates and should not be altered. Technically, you can save your workbook to one of Excel’s default locations, but it’s preferable to create your own.
  • Click Add a new location to set up your trusted location.

  • Do the following in the Microsoft Office Trusted Locations dialogue box:
    • Navigate to the folder you want to make a trusted location by clicking the Browse button.
    • Check the Subfolders of this location are also trusted box if you want any subfolder of the selected folder to be trusted as well.
    • Fill in the Description field with a brief message (this can help you manage multiple locations) or leave it blank.
    • Click the OK button.

Completed! You can now save your workbook with macros in a trusted location without worrying about Excel’s security settings.

How to Enable macros programmatically with VBA? 

Many people ask on Excel forums if it is possible to enable macros programmatically when opening a workbook and disable them before exiting. “No, it’s not possible,” is the immediate response. Because macro security is critical for Excel’s security, Microsoft designed any VBA code to be activated only by a user click.

When Microsoft closes a door, the user opens another 🙂 As a workaround, someone suggested using a “splash screen” or “instruction sheet” to force the user to enable macros. The fundamental concept is as follows:

You write code that generates all the worksheets except one, which is tucked away. The visible sheet (splash screen) states something like “Please enable macros and re-open the file” or provides more specific instructions.

When macros are disabled, the user can only see the “Splash Screen” worksheet; all other sheets are hidden. When macros are enabled, the code unhides all the sheets before re-hiding them completely when the workbook is closed.

How to Disable macros in Excel?

As previously stated, Excel’s default setting disables macros with a notification and allows users to enable them manually if desired. If you want to disable all macros silently, without receiving any notifications, go to the Trust Center and select the corresponding option (the first one).

  1. Click the File tab > Options in Excel.
  2. Select Trust Center from the left-hand pane, and then click Trust Center Settings.
  3. Select Macro Settings from the left menu, then Disable all macros without notification and click OK.

Содержание

  1. Excel Macros Disabled? – How to Enable Macros
  2. Warning!
  3. Enable Macros Temporarily – for Individual Workbooks
  4. Macro Settings in the Trust Center
  5. Enable Macros Permanently – for Individual Workbooks
  6. Enable Macros Permanently – for All Workbooks in a Trusted Location
  7. View Trusted Locations
  8. Add a new Trusted Location
  9. Change macro security settings in Excel
  10. Change macro security settings
  11. Troubleshooting
  12. I can’t change my macro security settings
  13. What happened to the Very High, High, Medium, and Low security settings?
  14. Need more help?

Excel Macros Disabled? – How to Enable Macros

Macros are disabled by default in Microsoft Excel and other MS Office applications, and need to be explicitly enabled by users. This article will cover the various methods that Excel provides to enable macros and manage your security settings, allowing you to run your own macros safely.

In this Article

Warning!

First, it’s important to understand just how dangerous macros can be.

Macros are actually little computer programs, stored in workbooks as VBA code. While mostly used to automate tasks inside Excel, VBA programmers can write powerful macros that can do almost anything with your computer and access any resources it’s connected to.

This power is meant extend the functionality of Excel, and it does – but in the wrong hands it can be twisted to spread ransomware, hijack computers for botnets, steal data from databases, send e-mail spam, and otherwise cause havoc on computers and their networks.

With this in mind, you should always be wary of macro-enabled workbooks that come from other people, and only enable macros for workbooks that you trust.

Enable Macros Temporarily – for Individual Workbooks

By default, when you first open a macro-enabled workbook you’ll see a yellow “SECURITY WARNING” bar appear just underneath the ribbon. Clicking the “Enable Content” button will enable macros.

NOTE: this will trigger any macros that run when the workbook is opened, so don’t click this by mistake!

If you don’t want to enable macros, you can click the ‘X’ on the far-right of the yellow bar. The security warning will disappear, but any attempt to run a macro will fail with a warning message. (Opening the VBA Editor or attempting to run a macro before dealing with the security warning will also clear the bar and disable macros.)

If you’ve disabled macros accidentally, you’ll have to close and re-open the workbook, then click the “Enable Content” button.

Macro Settings in the Trust Center

Excel provides settings to adjust its default behavior when opening macro-enabled workbooks. You can view these settings in the Trust Center:

  • Select File > Options, then select Trust Center in the left-hand list and click “Trust Center Settings…

  • In the Trust Center dialog, select “Macro Settings

Disable all macros without notification: you won’t be able to enable or run macros when you open a workbook. You’ll still be able to make and run macros in new workbooks, though.

Disable all macros with notification: this is the default option, allowing macros to be enabled from the Security Warning bar when you open a workbook.

Disable all macros except digitally signed macros: you won’t see any warnings, but only digitally signed macros will be able to run. Such macros are made by VBA developers, using certificates provided by a commercial authority or a security administrator in your organization.

Enable all macros (not recommended; potentially dangerous code can run): all macros are enabled without warning.

Trust access to the VBA project object model: this setting allows other programs (and macros) to modify macros in any open workbooks. Some external analytics programs will require you to enable this to work, but usually you should leave this unchecked.

Enable Macros Permanently – for Individual Workbooks

You can set a macro-enabled workbook to be a Trusted Document so that when you re-open it, macros will be enabled with no security warnings. Trusted workbooks are added to a private list associated with your Windows login.

To trust a workbook:

  • Open the workbook, then click File while the Security Warning bar is still visible
  • Click “Enable Content”, then select “Enable All Content” in the dropdown

NOTE: Excel doesn’t provide any way to un-trust a particular workbook, but it does allow you to un-trust all previously trusted workbooks. To do this:

  • Select File > Options, then select Trust Center in the left-hand list and click “Trust Center Settings…
  • In the Trust Center dialog, select “Trusted Documents

  • If you want to clear the list of trusted workbooks, click “Clear”
  • If you want to disable Trusted Documents, check “Disable Trusted Documents”; you’ll still be able to enable macros temporarily when a workbook is opened

Due to the limited functionality Excel provides for trusting individual documents, a better solution is to use Trusted Locations (see below).

Enable Macros Permanently – for All Workbooks in a Trusted Location

Rather than trusting individual workbooks, you can set Excel to trust certain locations on your computer or network. Any workbooks in a Trusted Location will open with macros enabled and no security warnings.

View Trusted Locations

Unlike Trusted Documents, a list of Trusted Locations is available for you to view at any time.

  • Select File > Options, then select Trust Center in the left-hand list and click “Trust Center Settings…
  • In the Trust Center dialog, select “Trusted Locations” in the left-hand list

By default, you’ll see several trusted locations already set by Excel. These locations are used by Excel to enable macros in new workbooks and add-ins, and should not be modified.

Add a new Trusted Location

Technically, you can put your own workbooks in the default Trusted Locations, but it’s better to define your own if you want to take advantage of this feature.

  • Click “Add new location…” to show the “Microsoft Office Trusted Location” dialog

  • Enter the path to the folder you want to use in the top textbox (or click “Browse…” to navigate to the folder)
  • If you want all subfolders of the selected folder to be trusted as well, check “Subfolders of this location are also trusted”
  • (Optional) Enter a description of this trusted location. Useful if you need to manage several locations

Источник

Change macro security settings in Excel

In Excel, you can change the macro security settings to control which macros run and under what circumstances when you open a workbook. For example, you might allow macros to run based on whether they are digitally signed by a trusted developer.

For more information about macro security settings in Microsoft Office documents, see Enable or disable macros in Office files.

The following list summarizes the various macro security settings. Under all settings, if antivirus software that works with Microsoft 365 is installed and the workbook contains macros, the workbook is scanned for known viruses before it is opened.

Disable all macros without notification Click this option if you don’t trust macros. All macros in documents and security alerts about macros are disabled. If there are documents that contain unsigned macros that you do trust, you can put those documents into a trusted location. Documents in trusted locations are allowed to run without being checked by the Trust Center security system.

Disable all macros with notification This is the default setting. Click this option if you want macros to be disabled, but you want to get security alerts if there are macros present. This way, you can choose when to enable those macros on a case by case basis.

Disable all macros except digitally signed macros This setting is the same as the Disable all macros with notification option, except that if the macro is digitally signed by a trusted publisher, the macro can run if you have already trusted the publisher. If you have not trusted the publisher, you are notified. That way, you can choose to enable those signed macros or trust the publisher. All unsigned macros are disabled without notification.

Enable all macros (not recommended, potentially dangerous code can run) Click this option to allow all macros to run. Using this setting makes your computer vulnerable to potentially malicious code and is not recommended.

Trust access to the VBA project object model This setting is for developers and is used to deliberately lock out or allow programmatic access to the VBA object model from any Automation client. In other words, it provides a security option for code that is written to automate an Office program and programmatically manipulate the Microsoft Visual Basic for Applications (VBA) environment and object model. This is a per user and per application setting, and denies access by default. This security option makes it more difficult for unauthorized programs to build «self-replicating» code that can harm end-user systems. For any Automation client to be able to access the VBA object model programmatically, the user running the code must explicitly grant access. To turn on access, select the check box.

Office uses Microsoft Authenticode technology to enable macro creators to digitally sign a file or a macro project. The certificate that is used to create this signature confirms that the macro or document originated from the signer, and the signature confirms that the macro or document has not been altered.

After you install your digital certificate, you can sign files and macro projects.

Obtaining a digital certificate for signing

You can obtain a digital certificate from a commercial certificate authority (CA), or from your internal security administrator or information technology (IT) professional.

To learn more about certificate authorities that offer services for Microsoft products, see the list of Microsoft Root Certificate Program Members.

Creating your own digital certificate for self-signing

You can also create your own self-signing certificate by using the Selfcert.exe tool.

Note: Because a digital certificate that you create isn’t issued by a formal certificate authority, macro projects that are signed by using such a certificate are referred to as self-signed projects. Microsoft Office trusts a self-signed certificate only on a computer that has that certificate in your Personal Certificates store.

For more information about how to digitally sign a macro, see Digitally sign a macro project.

Change macro security settings

You can change macro security settings in the Trust Center, unless a system administrator in your organization has changed the default settings to prevent you from changing the settings.

On the Developer tab, in the Code group, click Macro Security.

To enable the Developer tab, see Show the Developer tab.

In the Macro Settings category, under Macro Settings, click the option that you want.

Note: Any changes that you make in the Macro Settings category in Excel apply only to Excel and do not affect any other Microsoft Office program.

You can also access the Trust Center in Excel Options. To do that, click Options (Excel 2010 to 2016 versions) or Microsoft Office Button (Excel 2007), and then click Trust Center > Trust Center Settings > Macro Settings.

For more information about macro security, see the following topics:

Troubleshooting

I can’t change my macro security settings

Some users may not be able to change Trust Center settings due to group security policies in their organizations. In such cases, you need to contact the IT administrator for your organization.

What happened to the Very High, High, Medium, and Low security settings?

Excel 2003 setting

Excel 2007/2010/2013/2016 equivalent

Disable all macros without notification

In Excel 2003, VBA macros can run only if the Trust all installed add-ins and templates option (in Excel 2003, the Trusted Publishers tab in the Security dialog box) is selected and the macros (whether signed or unsigned) are stored in a specific trusted folder on the user’s hard disk.

If not all of these conditions are met, VBA macros cannot run under the Very High security setting in Excel 2003.

Disable all macros except digitally signed macros

In Excel 2003, executable files (such as .exe or .com) must be signed by an acknowledged trusted source (that is, they must have a certificate of trust) in order to run. Otherwise, all executables associated with or embedded in documents are automatically disabled without warning the user when those documents are opened.

By default, all Office 2003 programs are installed with macro security set to High.

Disable all macros with notification

In Excel 2003, users are prompted to enable or disable executables when a document is opened. This level requires the acceptance of a certificate of trust for each executable, which is accepted by adding the certificate to a segment of the computer’s Windows registry.

Subsequent requests to run a macro from a trusted source are automatically accepted (the executable runs without prompting the user).

Enable all macros (not recommended; potentially dangerous code can run)

In Excel 2003, all macros are run without restrictions. This security level does not protect against malicious programs, does not allow for acceptance of certificates of trust, and is not considered secure in general. This level is not recommended.

Need more help?

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

Источник

 

jfd

Пользователь

Сообщений: 302
Регистрация: 01.01.1970

#1

10.12.2013 16:54:16

Добрый день! Подскажите плиз.
МегаМакрос перебирает файлы эксель (xlsm) и одним из действий сохраняет его под другим именем. В перебираемых файлах есть МикроМакрос запускаемый по условию — вызов действия «сохранить как» и соответственно перехватывает выполнение МегаМакроса и портит мне весь кайф.
Как мне при открытии файла с МикроМакросом отключить его выполнение выполнение или удалить (он там больше не нужен)?
Спасибо
во так не работает почемуто

Код
Workbooks.Open FolderPath & sFiles
        Workbooks(sFiles).RunAutoMacros xlAutoDeactivate 

.

Изменено: jfd10.12.2013 17:05:31

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

#2

10.12.2013 17:08:48

В начало мегамакроса

Код
application.enableevents=false

и не забудьте в конце включить назад.

 

jfd

Пользователь

Сообщений: 302
Регистрация: 01.01.1970

Спасибо. Все заработало как надо

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

офф — интересно, где Вы берёте эти
RunAutoMacros xlAutoDeactivate  :)

Хотя на MSDN всё есть… Но на форумах я их не видел :)

Изменено: Hugo10.12.2013 18:06:04

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Тут такой момент….RunAutoMacros это больше пережиток старых версий и оставлен для совместимости. Т.к. макросы Auto_Open и Auto_Close не срабатывают при программном открытии/закрытии книг(то же самое и auto_Activate/Deactivate). И чтобы можно было их запустить при программном открытии книг и создан данный метод.
На данный момент Microsoft пишет, что предпочтительнее использовать события книги, а не автопроцедуры. Поэтому, возможно, на форуме их встретить сложно — практически не применяются(если бы все использовали автопроцедуры вместо Workbook_Open(и иже с ними) — уверен, встречали бы часто).

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

jfd

Пользователь

Сообщений: 302
Регистрация: 01.01.1970

Hugo

вобщемто да, в гугле есть все и ссылки на MSDN тоже )

 

jfd

Пользователь

Сообщений: 302
Регистрация: 01.01.1970

тогда еще дополняющий вопрос по Workbook.Open. А можно открыть книгу с макросами  (xlsm) как книгу эксель (xls*)?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Она так и откроется. Вопрос непонятен…

 

jfd

Пользователь

Сообщений: 302
Регистрация: 01.01.1970

фигню спросил. вопрос фактически отсылает к первоначальному вопросу  и поиску несуществующего параметра Workbook.Open типа RunMacro:= False
ps. хотя могли бы и сделать )

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#10

10.12.2013 22:16:58

Итак. Если Вы открываете программно книгу и в ней прописана автопроцедура Auto_Open — она не выполнится. Если откроете руками — выполнится.
Если открываете программно книгу, в которой в модуле книги записано Workbbok_Open, то событие будет выполнено в любом случае. Если только перед открытием программно Вы не отключите выполнение событий:

Код
Application.EnableEvents = False
Workbook.Open

Не забудьте после выполнения кода вернуть в исходное положение:

Код
Application.EnableEvents = True

Так что замечание «могли бы и сделать» несправедливо — сделано давно :-)

И не забудьте у себя удалить строку:

Код
Workbooks(sFiles).RunAutoMacros xlAutoDeactivate

Т.к. она как раз и запускает событийную процедуру.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Т.е. Вам хотелось бы открыть книгу xlsm с отключёнными макросами. А если открыть, сохранить Как xlsx, и продолжать работать с этой копией?

 

jfd

Пользователь

Сообщений: 302
Регистрация: 01.01.1970

The_Prist

теперь понятно. спасибо за разъяснения.

 

jfd

Пользователь

Сообщений: 302
Регистрация: 01.01.1970

Юрий М

такое приходило в голову, но это усложняет макрос. кроме того возникает порочный круг: чтобы сохранить книгу xlsm как xls надо отключить выполнение макроса (поскольку в ней есть Workbook_BeforeSave). а отключив макрос исчезает необходимость пересохранять книгу в xls  :D

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Дима дал нормальное объяснение, а я говорил не про сохранение в формате xls (макросы останутся), а про сохранение в обычную книгу (xlsx) — там макросы не живут.

 

falmrom

Пользователь

Сообщений: 349
Регистрация: 15.04.2018

#15

19.07.2019 14:01:26

The_Prist, спасибо!

Улыбнись.

Понравилась статья? Поделить с друзьями:
  • Disable all macros in excel
  • Dis prefix word meaning
  • Dirty word that starts with i
  • Dirty word of the day
  • Dirty word for him