Excel vba workbooks open
VBA-Урок 11.1. События рабочей книги (Workbook Events)
Мы можем иметь события рабочей книги (например, открытие, закрытие и т.д.), которые могут быть триггерами (переключателями) для VBA кода.
Workbook_Open (Открытие книги)
Чтобы выполнить инструкции, когда открывается рабочая книга, идем к ThisWorkbook и выбираем Workbook :
Событие Workbook_Open будет добавлено по умолчанию и будет действовать во время открытия книги:
Например, если мы добавим следующую инструкцию, тогда диалоговое окно будет отображено при открытии книги:
Workbook_BeforeClose (Событие перед закрытием книги)
Чтобы выполнить инструкции перед самым закрытием книги, выберите BeforeClose
Закрытие книги может быть отменено, если присвоить значение True к переменной «Cancel».
Ниже приведен пример, в котором пользователя спрашивают подтверждение на закрытие рабочей книги:
Workbook_BeforeSave (Событие перед сохранением книги)
Это событие возникает сразу перед самым сохранением рабочей книги:
Сохранение файла может быть отменено присвоением значения True к переменной «Cancel».
Workbook_BeforePrint (Событие перед печатью книги)
Это событие возникает перед самой печатью рабочей книги:
Печать файла может быть отменена присвоением значения True к переменной «Cancel».
Workbook_AfterSave (Событие после сохранения книги)
Это событие возникает сразу после сохранением рабочей книги:
Workbook_SheetActivate (Событие переключения рабочего листа)
Это событие возникает каждый раз, когда вы переключаетесь между листами рабочей книги:
В этом примере, название активированного листа отображается в диалоговом окне
Workbook_SheetBeforeDoubleClick (Событие двойного щелчка по ячейке)
Это событие возникает при двойном щелчке на ячейке рабочего листа
Например, мы можем использовать это событие, чтобы добавить цвет заливки ячейки, в зависимости от выбранного листа:
Workbook_SheetBeforeRightClick (Событие перед правым кликом)
Это событие возникает перед самым кликом правой кнопки мыши
Workbook_SheetChange (Событие изменения содержания листа)
Это событие возникает каждый раз, когда меняется содержание рабочего листа
Workbook_SheetCalculate (Событие пересчете листа)
Это событие возникает каждый раз, когда рассчитываются или пересчитываются данные на рабочем листе:
Workbook_SheetSelectionChange (Событие изменения выбранного диапазона ячеек)
Это событие возникает каждый раз, когда меняется содержание выбранного диапазона ячеек на расчетном листе
В этом примере, изменяется цвет заливки, если ячейка А1 пуста
Workbook_NewSheet (Событие добавления нового листа)
Это событие возникает каждый раз, когда добавляется новый лист в рабочую книгу:
Workbook_SheetFollowHyperlink (Событие нажатия на ссылку)
Это событие возникает при нажатии на ссылку (гипертекст):
Excel VBA Workbooks.Open Method
This Excel VBA tutorial explains how to use Workbooks.Open Method to open another workbook.
Excel VBA Workbooks.Open Method
Workbooks.Open Method is useful when you try to open another Workbook using VBA. For example, you can open a workbook > format the spreadsheet > close the workbook automatically. There are a lot of rarely used arguments for Workbooks.Open Method. As most of them are self explanatory, I will demonstrate some common uses of the Method.
Syntax of Workbooks.Open Method
Name | Required/Optional | Data Type | Description |
FileName | Optional | Variant | String. The file name of the workbook to be opened. |
UpdateLinks | Optional | Variant | Specifies the way external references (links) in the file, such as the reference to a range in the Budget.xls workbook in the following formula =SUM([Budget.xls]Annual!C10:C25), are updated. If this argument is omitted, the user is prompted to specify how links will be updated. For more information about the values used by this parameter, see the Remarks section. If Microsoft Excel is opening a file in the WKS, WK1, or WK3 format and the UpdateLinks argument is 0, no charts are created; otherwise Microsoft Excel generates charts from the graphs attached to the file. |
ReadOnly | Optional | Variant | True to open the workbook in read-only mode. |
Format | Optional | Variant | If Microsoft Excel opens a text file, this argument specifies the delimiter character. If this argument is omitted, the current delimiter is used. For more information about the values used by this parameter, see the Remarks section. |
Password | Optional | Variant | A string that contains the password required to open a protected workbook. If this argument is omitted and the workbook requires a password, the user is prompted for the password. |
WriteResPassword | Optional | Variant | A string that contains the password required to write to a write-reserved workbook. If this argument is omitted and the workbook requires a password, the user will be prompted for the password. |
IgnoreReadOnlyRecommended | Optional | Variant | True to have Microsoft Excel not display the read-only recommended message (if the workbook was saved with the Read-Only Recommended option). |
Origin | Optional | Variant | If the file is a text file, this argument indicates where it originated, so that code pages and Carriage Return/Line Feed (CR/LF) can be mapped correctly. Can be one of the following XlPlatform constants: xlMacintosh, xlWindows, or xlMSDOS. If this argument is omitted, the current operating system is used. |
Delimiter | Optional | Variant | If the file is a text file and the Format argument is 6, this argument is a string that specifies the character to be used as the delimiter. For example, use Chr(9) for tabs, use “,” for commas, use “;” for semicolons, or use a custom character. Only the first character of the string is used. |
Editable | Optional | Variant | If the file is a Microsoft Excel 4.0 add-in, this argument is True to open the add-in so that it is a visible window. If this argument is False or omitted, the add-in is opened as hidden, and it cannot be unhidden. This option does not apply to add-ins created in Microsoft Excel 5.0 or later. If the file is an Excel template, True to open the specified template for editing. False to open a new workbook based on the specified template. The default value is False. |
Notify | Optional | Variant | If the file cannot be opened in read/write mode, this argument is True to add the file to the file notification list. Microsoft Excel will open the file as read-only, poll the file notification list, and then notify the user when the file becomes available. If this argument is False or omitted, no notification is requested, and any attempts to open an unavailable file will fail. |
Converter | Optional | Variant | The index of the first file converter to try when opening the file. The specified file converter is tried first; if this converter does not recognize the file, all other converters are tried. The converter index consists of the row numbers of the converters returned by the FileConverters property. |
AddToMru | Optional | Variant | True to add this workbook to the list of recently used files. The default value is False. |
Local | Optional | Variant | True saves files against the language of Microsoft Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically United States English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project). |
CorruptLoad | Optional | XlCorruptLoad | Can be one of the following constants: xlNormalLoad, xlRepairFile and xlExtractData. The default behavior if no value is specified is xlNormalLoad and does not attempt recovery when initiated through the OM. |
Example 1 – Open a workbook
The below code opens workbook 1.xls and set the workbook as “wb” so that you can use wb to access other workbook Methods.
Example 2 – Open a workbook with password
There are two kinds of password protection – password to open the workbook, and password to modify the workbook.
In either case, if a workbook is password protected, opening the file will pop up a password box.
You can add the password argument to open the file with password automatically. If you open a non-password protected workbook but you add the password argument, you can still open the workbook.
Lets say you have a workbook 3.xlsx which is non-password protected, using the below code will still be able to open the workbook.
Example 3 – Open a workbook without alert
There are many kinds of alerts that may pop up when you open a workbook, preventing you from running the subsequent procedures. Turn off all alerts ensures you to run all the procedures successfully.