Excel vba this workbook close

Home / VBA / VBA Close Workbook (Excel File)

To close an Excel file, you need to use the “Close” method. With this method you can, specify if you want to save the changes or not. And, if you want to save and close a file that is not saved yet you can specify the path where you want to save it before closing.

The following is the syntax for the close method.

Workbook.Close (SaveChanges, FileName, RouteWorkbook)

Steps to Close a Workbook

  1. Specify the workbook that you want to close.
  2. Use the close method with that workbook.
  3. In the code method, specify if you want to save the file or not.
  4. In the end, mention the location path where you want to save the file before closing.

In this tutorial, we will look at different ways that you can use to close a workbook in Excel using VBA.

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Close a Workbook without Saving

If you want to save the active workbook without saving you need to use code like the following.

ActiveWorkbook.Close SaveChanges:=False

In this code, I have specified the “False” for the “SaveChanges” argument. So VBA will ignore if there are any changes in the workbook which are not saved. And if you want to close a specific workbook you can use the name of that workbook. Just like the following code.

Workbooks("book1").Close SaveChanges:=False

If you have data in the workbook and you skip the “SaveChanges” argument, then Excel will show a dialog box to confirm if you want to save the workbook or not. The point is: It is better to specify the “SaveChanges” argument even if it’s optional.

Close a Workbook after Saving

As you have seen, there’s an argument in the CLOSE method to specify the path location. Let’s say if you wish to save the “Book6” to the folder on the desktop. Here’s the code that you need to use.

Workbooks("Book6").Close _
SaveChanges:=True, _
Filename:="C:UsersDellDesktopmyFoldermyFile.xlsx"

This code is going to save the workbook “Book6” into the folder that is saved on my desktop with the name “myFIle.xlsx”. But here’s one thing that you need to take care of: IF you already have a workbook with the same name then it will replace that file with the new one.

Don’t worry, there’s a solution that you can use. The following code checks if there’s any file exists with the name that you want to use

Sub vba_close_workbook()
Dim wbCheck As String
wbCheck = Dir("C:UsersDellDesktopmyFoldermyFile.xlsx")
If wbCheck = "" Then
    Workbooks("Book6").Close _
    SaveChanges:=True, _
    Filename:="C:UsersDellDesktopmyFoldermyFile.xlsx"
Else
    MsgBox "Error! Name already used."
End If
End Sub

More on VBA Workbooks

VBA Save Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)

  • VBA Workbook

Открытие книги Excel из кода VBA. Проверка существования книги. Создание новой книги, обращение к открытой книге и ее закрытие. Методы Open, Add и Close.

Открытие существующей книги

Существующая книга открывается из кода VBA Excel с помощью метода Open:

Workbooks.Open Filename:=«D:test1.xls»

или

Workbooks.Open («D:test1.xls»)

В кавычках указывается полный путь к открываемому файлу Excel. Если такой файл не существует, произойдет ошибка.

Проверка существования файла

Проверить существование файла можно с помощью функции Dir. Проверка существования книги Excel:

If Dir(«D:test1.xls») = «» Then

    MsgBox «Файл не существует»

Else

    MsgBox «Файл существует»

End If

Или, если файл (книга Excel) существует, можно сразу его открыть:

If Dir(«D:test1.xls») = «» Then

    MsgBox «Файл не существует»

Else

    Workbooks.Open Filename:=«D:test1.xls»

End If

Создание новой книги

Новая рабочая книга Excel создается в VBA с помощью метода Add:

Созданную книгу, если она не будет использоваться как временная, лучше сразу сохранить:

Workbooks.Add

ActiveWorkbook.SaveAs Filename:=«D:test2.xls»

В кавычках указывается полный путь сохраняемого файла Excel, включая присваиваемое имя, в примере — это «test2.xls».

Обращение к открытой книге

Обращение к активной книге:

Обращение к книге с выполняемым кодом:

Обращение к книге по имени:

Workbooks(«test1.xls»)

Workbooks(«test2.xls»)

Обратиться по имени можно только к уже открытой книге, а чтобы из кода VBA Excel книгу открыть, необходимо указать полный путь к файлу.

Открытая рабочая книга закрывается из кода VBA Excel с помощью метода Close:

Workbooks(«test1.xlsx»).Close

Если закрываемая книга редактировалась, а внесенные изменения не были сохранены, тогда при ее закрытии Excel отобразит диалоговое окно с вопросом: Вы хотите сохранить изменения в файле test1.xlsx? Чтобы файл был закрыт без сохранения изменений и вывода диалогового окна, можно воспользоваться параметром метода Close — SaveChanges:

Workbooks(«test1.xlsx»).Close  SaveChanges:=False

или

Workbooks(«test1.xlsx»).Close  (False)

Закрыть книгу Excel из кода VBA с сохранением внесенных изменений можно также с помощью параметра SaveChanges:

Workbooks(«test1.xlsx»).Close  SaveChanges:=True

или

Workbooks(«test1.xlsx»).Close (True)


Фразы для контекстного поиска: открыть книгу, открытие книги, создать книгу, создание книги, закрыть книгу, закрытие книги, открыть файл Excel, открытие файла Excel, существование книги, обратиться к открытой книге.


When working with an Excel workbook, there are a few basic operations that any user needs to know how to carry out. The following are 2 of the most important ones:

  1. Opening a workbook.
  2. Closing a workbook.

Excel VBA Tutorial about how to close a workbookThese 2 actions are just as important if you’re working with Visual Basic for Applications.

In this tutorial, I focus on topic #2: How you can easily close an Excel workbook with VBA.

For these purposes, in the first few sections of this tutorial, I introduce some VBA constructs that help you create macros that close workbooks. My focus is, mainly, in the Workbook.Close method. However, I also introduce the Workbooks.Close method, which allows you to quickly close all open workbooks. At the end of that first section, I discuss the topic of closing Excel workbooks without prompts and introduce some of the most common ways of achieving this.

In the second section of this post, I go through 8 macro code examples. These VBA code samples use the constructs introduced in the first section for purposes of closing Excel workbooks in different situations. All of the macros are accompanied by an explanation. You can easily adjust the code samples in order to fit your own needs.

This Excel VBA Close Workbook Tutorial is accompanied by an Excel workbook containing the macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Please use the following table of contents to quickly navigate to the section that interests you the most. For best results, you may want to read the whole blog post.

Let’s start by taking a look at the…

Workbook.Close Method

You can use the Workbook.Close method for purposes of closing the applicable workbook object.

The basic syntax of Workbook.Close is as follows:

expression.Close(SaveChanges, Filename, RouteWorkbook)

The following are the applicable definitions for purposes of the statement above:

  • expression: Workbook object.
  • SaveChanges: Optional argument. You use SaveChanges for purposes of specifying whether to save changes (True) or not (False).
  • Filename: Optional argument. Filename allows you to specify the filename used by Excel when saving.
  • RouteWorkbook: Optional argument. Makes reference to workbook routing. In that context, it allows you to determine whether the workbook is sent to the next recipient (True) or not (False).

Since expression represents a Workbook object, I simplify the syntax above to the following:

Workbook.Close(SaveChanges, Filename, RouteWorkbook)

Let’s start by taking a closer look at the 3 parameters (SaveChanges, Filename and RouteWorkbook) above. After covering these arguments, I provide a few additional comments about the Workbook.Close method.

SaveChanges Parameter

You use the SaveChanges parameter to specify whether Visual Basic for Applications saves changes to the workbook (or not) when the workbook:

  1. Has unsaved changes.
  2. Doesn’t appear in any other open windows.

Both of these conditions must be met in order for VBA to consider SaveChanges. In other words, VBA ignores SaveChanges in the following situations:

  • When there aren’t any unsaved changes to the workbook.
  • Where there are changes to the workbook, but the workbook appears within other open windows.

SaveChanges is an optional argument. You generally use the following values when working with it:

  • True: Close workbook and save changes.
  • False: Close workbook without saving changes.

If you omit the SaveChanges parameter and the relevant workbook contains unsaved changes, Excel displays a dialog box. This dialog asks the user whether the changes should be saved or not.

Want to save your changes to workbook

Filename Parameter

Filename allows you to specify the filename under which Excel saves the changes to the closed workbook.

Filename is an optional parameter. Additionally, Filename is only relevant if you set SaveChanges to True. Whenever you set the SaveChanges parameter to False, the changes aren’t saved at all.

If you omit Filename and the workbook has no previous filename, Excel displays the Save As dialog box and asks the user to provide the filename.

Save As dialog launched when no Filename for Workbook.Close

Despite the above, if you want to ensure that a particular workbook is saved under a certain name and close it, you can generally proceed as follows:

  1. Use the Workbook.SaveAs method to save the workbook; and
  2. Close the workbook by using the Workbook.Close method.

This way of proceeding is suggested by authorities such as author Richard Mansfield (in Mastering VBA for Microsoft Office 2016). Some of the advantages of using the SaveAs method (vs. the Filename parameter) for these purposes are the following:

  1. Ensures that the workbook is always saved under the filename you specify.
  2. Allows you to take advantage of the 10 parameters of the SaveAs method. By using these parameters, you can specify items such as (i) file format, and (ii) protection password.

RouteWorkbook Parameter

The RouteWorkbook parameter is associated to workbook routing. You can use RouteWorkbook to specify whether the workbook is routed to the next recipient or not.

RouteWorkbook is optional.

The main rules that Visual Basic for Applications uses to determine how to deal with RouteWorkbook are as follows:

  1. If there’s no need to send the workbook to the next recipient, VBA ignores RouteWorkbook.

    For example, the workbook doesn’t need to be routed if (i) there’s no routing slip attached, or (ii) the routing has already occurred.

  2. If the workbook needs to be routed, VBA applies the value you specify for RouteWorkbook. You can use the following 2 values:
    1. True: VBA routes the workbook to the next recipient.
    2. False: The workbook isn’t sent.
  3. If you omit RouteWorkbook and the workbook need to be send, Excel asks the user whether the workbook is routed or not.

Workbook.Close Method And Auto_Close Macros

Auto_Close macros aren’t executed when you close the workbook from VBA. This is relevant if your workbook uses Auto_Close macros (vs. the BeforeClose event) for purposes of automatically running a macro before a workbook closes. The Workbook.Close method does trigger the BeforeClose event.

If you need to deal with Auto_Close macros and want the macro to be executed when you use the Workbook.Close method, use the Workbook.RunAutoMacros method.

Workbook.Close Method And Add-Ins

Usually, you install and uninstall add-ins through the Add-Ins dialog.

You can also open and close add-ins. In other words, you can theoretically apply the Workbook.Close method to an add-in.

As a consequence of the above, if you’ve accessed an add-in as a workbook (vs. using the Add-Ins dialog box), you can close it with the Close method. However, as a general rule, this isn’t the most appropriate way to deal with add-ins.

The reason for this is explained by Excel authorities Dick Kusleika and Mike Alexander in Excel 2016 Power Programming with VBA, as follows:

Using the Close method on an installed add-in removes the add-in from memory but does not set its Installed property to False. Therefore, the Add-Ins dialog box still lists the add-in as installed, which can be confusing.

Therefore, as a general rule, use the AddIn.Installed property for purposes of installing and removing add-ins.

Workbooks.Close Method

You can also apply the Close method to the collection of all open Excel workbooks. In other words, you can use the Workbooks.Close method to close all Excel workbooks at once.

The basic syntax of Workbooks.Close is as follows:

expression.Close

“expression” represents the Workbooks collection. Therefore, I simplify the above as follows:

Workbooks.Close

The Workbooks.Close method is, to a certain extent, similar to the Workbook.Close method I explain above. For example, Auto_Close macros aren’t executed when you close a workbook with either of these methods. Therefore, my comments above regarding Auto_Close macros and Workbook.Close are also generally applicable to Workbooks.Close.

There’s, however, a very important difference between Workbook.Close and Workbooks.Close:

Workbooks.Close takes no parameters. As I explain above, Workbook.Close has 3 parameters (SaveChanges, Filename and RouteWorkbook).

As a consequence of the above, if you want to use any (or all) of the parameters I describe above while closing all open workbooks, you generally have to rely on loops.

Further below, I provide macro code examples that you can use to close all open workbooks using either of these 2 methods:

  1. Workbooks.Close.
  2. Workbook.Close (+ loops).

Excel VBA To Close Workbook Without Prompts

In certain cases, you want to ensure that Excel closes a particular workbook without showing any prompts.

When working with the Close VBA method, the prompts that you usually have to deal with ask one of the following questions:

  1. Should Excel save the changes?

    Dialog: Want to save changes to Book?

  2. What filename should Excel use?

    Excel Save As dialog box

There are a few different ways in which you can handle this using Visual Basic for Applications. The most common ways of tackling this issue are the following 4:

  1. Saving the workbook prior to using the Close method.
  2. Appropriately using the SaveChanges and Filename parameters of the Workbook.Close method.
  3. Using the Application.DisplayAlerts property.
  4. Setting the Workbook.Saved property to True.

I cover the topic of how to save a workbook using VBA (#1 above) in a separate blog post that you can find in the Archives. I cover both the SaveChanges and Filename arguments (#2 above) in this tutorial.

Therefore, in the following sections, I introduce the remaining VBA constructs #3 (Application.DisplayAlerts) and #4 (Workbook.Saved). Using either of these 2 properties results in Excel closing the workbook without prompts. In both cases, Excel closes the file without saving the changes.

Application.DisplayAlerts Property

The Application.DisplayAlerts property allows you to specify whether or not Excel displays certain prompts and alerts. For these purposes, you can set Application.DisplayAlerts to either of the following values:

  1. True: The default value. Excel displays alerts and messages.
  2. False: The alerts and messages aren’t displayed. If a particular alert or message requires a user response, Excel uses the default.

The basic syntax of Application.DisplayAlerts is as follows:

expression.DisplayAlerts

“expression” is the Excel Application object. Therefore, I simplify the above as follows:

Application.DisplayAlerts

Macro example #7 below uses the Application.DisplayAlerts property for purposes of closing a workbook without prompts. There are, however, other (better) ways of using VBA to close an Excel workbook without displaying prompts. I provide further explanation of this matter in the relevant section (for macro sample #7) further below.

Workbook.Saved Property

From a general perspective, the Workbook.Saved property indicates whether changes have been made to a particular Excel workbook since the last time it was saved. In other words, Workbook.Saved indicates whether the workbook has unsaved changes.

The basic syntax of Workbook.Saved is as follows:

expression.Saved

“expression” is a Workbook object. Therefore, I simplify the above as follows:

Workbook.Saved

The Saved property is, however, read/write. Therefore, you can set Workbook.Saved to either of the following values:

  1. True: No changes have been made since the last time the workbook was saved.
  2. False: Changes have been made.

By setting Saved to True prior to closing a workbook, you can close a workbook without Excel displaying a prompt. In such case, the changes to the workbook aren’t saved.

I provide a practical code example showing how you can easily do this further below (macro example #8).

In the following sections, I provide 8 macro code examples that allow you to close an Excel workbook using VBA. These 8 macro samples cover several of the most common situations you’re likely to encounter.

The Sub procedure examples I provide work with the active workbook. For these purposes, I use the Application.ActiveWorkbook property (ActiveWorkbook). By replacing the object reference, you can easily adjust these macros in order to work with other workbooks.

Macro Code Example #1: Excel VBA Close Workbook

At the most basic level, you can use a statement with the following structure to close an Excel workbook:

Workbook.Close

The following sample macro (Close_Workbook) closes the active workbook:

ActiveWorkbook.Close

The macro example has a single statement that follows the structure I describe above:

ActiveWorkbook.Close

This statement is built by using the following items:

  1. ActiveWorkbook: The Application.ActiveWorkbook property returns the active workbook.
  2. Close: The Close method closes the active workbook returned by item #1.

Macro Code Example #2: Excel VBA Close Workbook Without Saving Changes

If you want to close a workbook without saving changes, you can use a statement that uses the following syntax:

Workbook.Close SaveChanges:=False

The following macro example (Close_Workbook_Without_Saving_Changes) closes the active workbook without saving changes:

ActiveWorkbook.Close SaveChanges:=False

The following are the items within the macro’s single statement:

  1. ActiveWorkbook: The active workbook.
  2. Close: The Close method.
  3. SaveChanges:=False: The SaveChanges parameter of the Workbook.Close method is set to False. Therefore, Excel doesn’t save changes prior to closing the workbook.

This macro is substantially the same as the previous example #1. The only new item is the SaveChanges argument (#3).

Macro Code Example #3: Excel VBA Close Workbook And Save Changes

You can use the following statement structure to close a workbook and save the changes:

Workbook.Close SaveChanges:=True

The following sample Sub procedure (Close_Workbook_Save_Changes) closes the active workbook and saves changes:

ActiveWorkbook.Close SaveChanges:=True

The only statement within the macro has the following 3 components:

  1. ActiveWorkbook: Reference to the active workbook.
  2. Close: The Close method.
  3. SaveChanges:=True: Sets the SaveChanges parameter of Workbook.Close to True. As a consequence of this, Excel saves the changes when closing the workbook.

This procedure is almost identical to macro sample #2 above. The only difference is the value to which the SaveChanges parameter (#3 above) is set (True vs. False).

Macro Code Example #4: Excel VBA Close Workbook And Save Changes With Filename

The VBA statement structure that I show below allows you to do the following:

  1. Save the workbook before closing.
  2. Set the filename that Excel uses if the workbook has no previously associated filename.

The following VBA statement structure allows you to do the above:

Workbook.Close SaveChanges:=True, Filename:=”fileNameString”

For these purposes, “fileNameString” is the file name you want Excel to use.

As I mention further above (section about the Filename parameter), using the statement I provide in this section doesn’t always result in the workbook being saved with the filename you want. In order to ensure that the workbook is saved always under the desired filename, you can generally use the Workbook.SaveAs method prior to calling the Workbook.Close method.

The following macro example (Close_Workbook_Save_Changes_Filename) closes the active workbook and saves changes under the specified filename. The filename under which the workbook is saved (if applicable) is “Excel VBA Close Workbook”.

ActiveWorkbook.Close SaveChanges:=True, Filename:="Excel VBA Close Workbook Test"

The statement within the macro above has the following components:

  1. ActiveWorkbook: Application.ActiveWorkbook property.
  2. Close: Workbook.Close method.
  3. SaveChanges:=True: Sets the SaveChanges parameter of Workbook.Close to True.
  4. Filename:=”Excel VBA Close Workbook”: The Filename argument of the Close method. Specifies that the filename that Excel uses is “Excel VBA Close Workbook”.

This sample macro is very similar to the previous example #3. The only new item is the Filename parameter (#4).

Macro Code Examples #5 And #6: Excel VBA Close All Workbooks

In this section, I provide 2 macro examples that you can use to close all Excel workbooks at once.

As I mention above, you can use the Workbooks.Close method in order to close all the members of the Workbooks collection (i.e. all open workbooks). Therefore, you can use the following statement for purposes of closing all open Excel workbooks:

Workbooks.Close

The following macro code sample (Close_All_Workbooks) closes all workbooks with the Workbooks.Close method. The single statement within this macro is the one I explain above.

Workbooks.Close

However, as I explain above, Workbooks.Close takes no parameters.

The Workbook.Close method does take parameters. The Workbook.Close method works with only one workbook at a time. In order to close all open workbooks at once, you can use a For Each… Next loop. The resulting structure of the relevant VBA loop is as follows:

For Each Workbook In Workbooks

Workbook.Close

Next Workbook

The following procedure example (Close_All_Workbooks_Loop) uses the Workbook.Close method and a For Each… Next loop to close all workbooks:

For Each... Next Loop and myWorkbook.Close

The process followed by this macro to close all open workbooks is as follows:

  1. Close the first open workbook.
  2. Check whether there are elements left within the collection of open workbooks.
  3. If there are open workbooks left:
    1. Close the next workbook.
    2. Repeat step #2 above.
  4. If there are no open workbooks left (step #2), exit the For Each… Next loop and end the macro.

The following diagram illustrates this procedure:

Loop diagram: Close first workbook and More workbooks and Close next workbook

Let’s take a closer look at each of the lines of code within this sample macro:

Line #1: Dim myWorkbook As Workbook

The Dim statement declares the myWorkbook object variable.

Line #2: For Each myWorkbook In Workbooks

Opening statement of a For Each… Next loop. This repeats the execution of the statement within the loop (line #3 below) for each workbook within the Workbooks collection.

The 2 relevant items within this line of code are the following:

  1. myWorkbook: myWorkbook variable. Used to iterate through all the elements within the Workbooks collection (item #2).
  2. Workbooks: The Application.Workbooks property returns the collection of all open workbooks.

Line #3: myWorkbook.Close

This statement is exactly the same as that in macro sample #1 above. You can easily modify this statement to use the SaveChanges and/or Filename properties. Examples #2 through #4 are examples of how you can do this.

When within the For Each… Next loop, this line #3 results in Excel closing the applicable workbook. The closed workbook, therefore, is dependent on the current iteration of the loop.

Line #4: Next myWorkbook

Closing statement of the For Each… Next loop.

Macro Code Examples #7 And #8: Excel VBA Close Workbook Without Prompt

This section provides 2 macro code examples that allow you to close a workbook without prompts.

The first macro sample (#7) uses the following basic structure:

Application.DisplayAlerts = False

Workbook.Close

This results in Excel closing the workbook without prompts. Additionally, the workbook isn’t saved.

As I mention above when introducing the Application.DisplayAlerts property, you’re generally better off avoiding this particular VBA code structure. The other options I discuss in this tutorial (saving the workbook prior to calling Close, or using the SaveChanges and Filename parameters of Close) are more appropriate in most situations.

The following macro example (Close_Workbook_Without_Prompt_1) turns off Excel’s prompts and alerts prior to closing the workbook. Therefore, Excel closes the active workbook without prompts.

Application.DisplayAlerts = False. ActiveWorkbook.Close

This sample macro is composed of the following 2 statements:

  1. Application.DisplayAlerts = False: Sets the Application.DisplayAlerts property to False. As a consequence, Excel turns off prompts.
  2. ActiveWorkbook.Close: The Application.ActiveWorkbook property and the Workbook.Close method are used to close the active workbook.

The second macro within this section uses the following syntax:

With Workbook

.Saved = True

.Close

End With

By setting the Workbook.Saved property to True, you indicate that no changes have been made since the last time the workbook was saved. In other words, you’re telling Excel that the workbook you’re closing doesn’t need to be saved.

The following macro code sample (Close_Workbook_Without_Prompt_2) sets the Saved property to True prior to calling the Workbook.Close method. As a consequence of this, the active workbook is closed without displaying prompts.

ActiveWorkbook.Saved = True. ActiveWorkbook.Close

Let’s take a closer look at each of the lines of code within this sample Sub procedure:

Line #1: With ActiveWorkbook

Opening line for a With… End With block. As a consequence of this, the statements within the block (lines #2 and #3) work with the object specified in this line #1. That object is the active workbook (ActiveWorkbook).

Line #2: .Saved = True

Sets the Workbook.Saved property to True. Indicates that no changes have been made to the active workbook (in line #1 above) since last time the workbook was saved.

Line #3: .Close

Calls the Workbook.Close method. Closes the active workbook (in line #1 above).

Line #4: End With

Closing line of the End… End With statement.

Conclusion

After reading this Excel VBA tutorial, you have the knowledge you need to start crafting macros that quickly close Excel workbooks in several different scenarios.

In the first section of this tutorial, you read about the 2 VBA methods you can use to close Excel workbooks:

  1. Workbook.Close.
  2. Workbooks.Close.

In addition to reading about how you can easily use each of these methods, you’ve seen why most VBA Sub procedures rely on the Workbook.Close method. You’ve also read about how, by appropriately using the parameters of Workbook.Close or combining this method with other VBA constructs, you can specify how Excel acts when closing a workbook.

Finally, you’ve seen 8 examples of macro code that put the above VBA constructs and information in practice.

Overall, the information and examples within this tutorial allow you to easily and quickly create Excel macros that achieve a variety of objects. The following are some examples of what you can now do with Visual Basic for Applications:

  1. Close a particular Excel workbook.
  2. Close a workbook without saving changes.
  3. Close a workbook and save the changes. This includes the possibility of setting the filename Excel uses when saving.
  4. Close all open workbooks at once.
  5. Close an Excel workbook without any prompts.

This Excel VBA Close Workbook Tutorial is accompanied by an Excel workbook containing the macros I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Books Referenced In This Excel Tutorial

  • Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
  • Mansfield, Richard (2016). Mastering VBA for Microsoft Office 2016. Indianapolis, IN: John Wiley & Sons Inc.

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Workbook.Close method (Excel)

vbaxl10.chm199085

vbaxl10.chm199085

excel

Excel.Workbook.Close

c0376cab-a2db-c606-67bf-0a4921b81e03

05/29/2019

medium

Workbook.Close method (Excel)

Closes the object.

Syntax

expression.Close (SaveChanges, FileName, RouteWorkbook)

expression A variable that represents a Workbook object.

Parameters

Name Required/Optional Data type Description
SaveChanges Optional Variant If there are no changes to the workbook, this argument is ignored. If there are changes to the workbook and the workbook appears in other open windows, this argument is ignored. If there are changes to the workbook but the workbook doesn’t appear in any other open windows, this argument specifies whether changes should be saved. If set to True, changes are saved to the workbook.

If there is not yet a file name associated with the workbook, FileName is used. If FileName is omitted, the user is asked to supply a file name.

FileName Optional Variant Saves changes under this file name.
RouteWorkbook Optional Variant If the workbook doesn’t need to be routed to the next recipient (if it has no routing slip or has already been routed), this argument is ignored. Otherwise, Microsoft Excel routes the workbook according to the value of this parameter.

If set to True, the workbook is sent to the next recipient. If set to False, the workbook is not sent. If omitted, the user is asked whether the workbook should be sent.

Remarks

Closing a workbook from Visual Basic doesn’t run any Auto_Close macros in the workbook. Use the RunAutoMacros method to run the Auto_Close macros.

Example

This example closes Book1.xls and discards any changes that have been made to it.

Workbooks("BOOK1.XLS").Close SaveChanges:=False

[!includeSupport and feedback]

Содержание

  1. Метод Workbook.Close (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Workbook.Close method (Excel)
  8. Syntax
  9. Parameters
  10. Remarks
  11. Example
  12. Support and feedback
  13. VBA Open / Close Workbook
  14. Open a Workbook in VBA
  15. Open Workbook From Path
  16. Open Workbook – ActiveWorkbook
  17. Open Workbook and Assign to a Variable
  18. Workbook Open File Dialog
  19. Open New Workbook
  20. VBA Coding Made Easy
  21. Open New Workbook To Variable
  22. Open Workbook Syntax
  23. Open Workbook Read-Only
  24. Open Password Protected Workbook
  25. Open Workbook Syntax Notes
  26. Close a Workbook in VBA
  27. Close Specific Workbook
  28. Close Active Workbook
  29. Close All Open Workbooks
  30. Close First Opened Workbook
  31. Close Without Saving
  32. Save and Close Without Prompt
  33. Other Workbook Open Examples
  34. Open Multiple New Workbooks
  35. Open All Excel Workbooks in a Folder
  36. Check if a Workbook is Open
  37. Workbook_Open Event
  38. Open Other Types of Files in VBA
  39. Open a Text file and Read its Contents
  40. Open a Text File and Append to it
  41. Opening a Word File and Writing to it
  42. VBA Code Examples Add-in
  43. Свойства и методы ActiveWorkbook
  44. Краткое руководство по книге VBA
  45. Начало работы с книгой VBA
  46. Доступ к рабочей книге VBA по индексу
  47. Поиск всех открытых рабочих книг
  48. Открыть рабочую книгу
  49. Проверить открыта ли книга
  50. Закрыть книгу
  51. Сохранить книгу
  52. Копировать книгу
  53. Использование диалогового окна «Файл» для открытия рабочей книги
  54. Использование ThisWorkbook
  55. Использование ActiveWorkbook
  56. Примеры доступа к книге
  57. Объявление переменной VBA Workbook
  58. Создать новую книгу
  59. With и Workbook
  60. Резюме
  61. Заключение

Метод Workbook.Close (Excel)

Синтаксис

expression. Close (SaveChanges, FileName, RouteWorkbook)

Выражение Переменная, представляющая объект Workbook .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Savechanges Необязательный Variant Если в книге нет изменений, этот аргумент игнорируется. Если в книге есть изменения, а книга отображается в других открытых окнах, этот аргумент игнорируется. Если в книге есть изменения, но книга не отображается в других открытых окнах, этот аргумент указывает, следует ли сохранять изменения. Если задано значение True, изменения сохраняются в книге.

Если имя файла еще не связано с книгой, используется имя файла . Если параметр FileName опущен, пользователю будет предложено указать имя файла. FileName Необязательный Variant Сохраняет изменения под этим именем файла. RouteWorkbook Необязательный Variant Если книга не требуется маршрутизировать к следующему получателю (если она не имеет скольжения маршрутизации или уже была перенаправлена), этот аргумент игнорируется. В противном случае Microsoft Excel направляет книгу в соответствии со значением этого параметра.

Если задано значение True, книга отправляется следующему получателю. Если задано значение False, книга не отправляется. Если этот параметр опущен, пользователю будет предложено отправить книгу.

Замечания

При закрытии книги из Visual Basic в ней не выполняются макросы Auto_Close. Используйте метод RunAutoMacros для запуска макросов Auto_Close.

Пример

Этот пример закрывает Book1.xls и удаляет все внесенные в него изменения.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Workbook.Close method (Excel)

Closes the object.

Syntax

expression.Close (SaveChanges, FileName, RouteWorkbook)

expression A variable that represents a Workbook object.

Parameters

Name Required/Optional Data type Description
SaveChanges Optional Variant If there are no changes to the workbook, this argument is ignored. If there are changes to the workbook and the workbook appears in other open windows, this argument is ignored. If there are changes to the workbook but the workbook doesn’t appear in any other open windows, this argument specifies whether changes should be saved. If set to True, changes are saved to the workbook.

If there is not yet a file name associated with the workbook, FileName is used. If FileName is omitted, the user is asked to supply a file name. FileName Optional Variant Saves changes under this file name. RouteWorkbook Optional Variant If the workbook doesn’t need to be routed to the next recipient (if it has no routing slip or has already been routed), this argument is ignored. Otherwise, Microsoft Excel routes the workbook according to the value of this parameter.

If set to True, the workbook is sent to the next recipient. If set to False, the workbook is not sent. If omitted, the user is asked whether the workbook should be sent.

Closing a workbook from Visual Basic doesn’t run any Auto_Close macros in the workbook. Use the RunAutoMacros method to run the Auto_Close macros.

Example

This example closes Book1.xls and discards any changes that have been made to it.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Open / Close Workbook

In this Article

In this tutorial, you will learn how to use VBA to open and close Excel Workbooks and other types of Files in several ways.

VBA allows you to open or close files using the standard methods .Open and .Close.

If you want to learn how to check if a file exists before attempting to open the file, you can click on this link: VBA File Exists

Open a Workbook in VBA

Open Workbook From Path

If you know which file you want to open, you can specify its full path name in the function. Here is the code:

This line of the code opens “Sample file 1” file from the “VBA Folder”.

Open Workbook – ActiveWorkbook

When you open a workbook, it automatically becomes the ActiveWorkbook. You can reference the newly opened workbook like so:

When you reference a sheet or range and omit the workbook name, VBA will assume you are referring to the ActiveWorkbook:

Open Workbook and Assign to a Variable

You can also open a workbook and assign it directly to an object variable. This procedure will open a workbook to the wb variable and then save the workbook.

Assigning workbooks to variables when they open is the best way to keep track of your workbooks

Workbook Open File Dialog

You can also trigger the workbook Open File Dialog box. This allows the user to navigate to a file and open it:

As you can see in Image 1, with this approach users can choose which file to open. The Open File Dialog Box can be heavily customized. You can default to a certain folder, choose which types of files are visible (ex. .xlsx only), and more. Read our tutorial on the Open File Dialog Box for detailed examples.

Open New Workbook

This line of code will open a new workbook:

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Open New Workbook To Variable

This procedure will open a new workbook, assigning it to variable wb:

Open Workbook Syntax

When you use Workbooks.Open you might notice that there are many options available when opening the workbook:

The Filename is required. All other arguments are optional – and you probably won’t need to know most of the other arguments. Here are the two most common:

Open Workbook Read-Only

When workbook is opened read-only, you can’t save over the original file. This prevents the file from being edited by the user.

Open Password Protected Workbook

A workbook might be password-protected. Use this code to open the password-protected workbook:

Open Workbook Syntax Notes

Notice that in the image above, we included a parenthesis “(” to show the syntax. If you use parenthesis when working with Workbooks.Open, you must assign the workbook to a variable:

Close a Workbook in VBA

Close Specific Workbook

Similarly to opening a workbook, there are several ways to close a file. If you know which file you want to close, you can use the following code:

This line of code closes the file “Sample file 1” if it’s opened. If not, it will return an error, so you should take care of error handling.

Close Active Workbook

If you want to close the Workbook which is currently active, this line of code will enable you to do that:

Close All Open Workbooks

To close all open Workbooks, you can simply use this code:

Close First Opened Workbook

This will close the first opened/created workbook:

Replace 1 with 2 to close the second opened / created workbook and so on.

Close Without Saving

This will close a Workbook without saving and without showing the save prompt:

Save and Close Without Prompt

Similarly this will save and close a Workbook without showing the save prompt:

Note: There are several other ways to indicate whether to save or not save a Workbook and also whether to show prompts or not. This is discussed in more detail here.

Other Workbook Open Examples

Open Multiple New Workbooks

This procedure will open multiple new workbooks, assigning the new workbooks to an array:

Open All Excel Workbooks in a Folder

This procedure will open all Excel Workbooks in a folder, using the Open File Dialog picker.

Check if a Workbook is Open

Workbook_Open Event

VBA Events are “triggers” that tell VBA to run certain code. You can set up workbook events for open, close, before save, after save and more.

Read our Workbook_Open Event tutorial to learn more about automatically running macros when a workbook is opened.

Open Other Types of Files in VBA

You can use the VBA to open other types of files with VBA – such as txt or Word files.

Open a Text file and Read its Contents

The VBA open method allows you to read or write to the file once you have opened it. To read the contents of a file, we can open the file for INPUT.

The code above will open the text file “test.txt” and then it will read the entire contents of the file to the strBody variable. Once you have extracted the file data into the strBody variable, you can use it for what you require. Using the Debug.Print command above enables us to see the contents of the strBody variable in the Immediate window in the VBE.

Open a Text File and Append to it

We can also open a text file in VBA, and then append to the bottom of the file using the Append method.

The above code will open the text file and then append 2 lines of text to the bottom of the file using the #intFile variable (the # sign is the key!). The code then closes the file.

Opening a Word File and Writing to it

We can also use VBA in Excel to open a Word file.

This code will open a copy of Word, and then open the document test.docx.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Свойства и методы ActiveWorkbook

Мы тонем в информации, но жаждем знаний

Эта статья содержит полное руководство по использованию рабочей книги VBA.

Если вы хотите использовать VBA для открытия рабочей книги, тогда откройте «Открыть рабочую книгу»

Если вы хотите использовать VBA для создания новой рабочей книги, перейдите к разделу «Создание новой рабочей книги».

Для всех других задач VBA Workbook, ознакомьтесь с кратким руководством ниже.

Краткое руководство по книге VBA

В следующей таблице приведено краткое руководство по основным задачам книги VBA.

Задача Исполнение
Доступ к открытой книге с
использованием имени
Workbooks(«Пример.xlsx»)
Доступ к открытой рабочей
книге (открывшейся первой)
Workbooks(1)
Доступ к открытой рабочей
книге (открывшейся последней)
Workbooks(Workbooks.Count)
Доступ к активной книге ActiveWorkbook
Доступ к книге, содержащей
код VBA
ThisWorkbook
Объявите переменную книги Dim wk As Workbook
Назначьте переменную книги Set wk = Workbooks(«Пример.xlsx»)
Set wk = ThisWorkbook
Set wk = Workbooks(1)
Активировать книгу wk.Activate
Закрыть книгу без сохранения wk.Close SaveChanges:=False
Закройте книгу и сохраните wk.Close SaveChanges:=True
Создать новую рабочую книгу Set wk = Workbooks.Add
Открыть рабочую книгу Set wk =Workbooks.Open («C:ДокументыПример.xlsx»)
Открыть книгу только для
чтения
Set wk = Workbooks.Open («C:ДокументыПример.xlsx», ReadOnly:=True)
Проверьте существование книги If Dir(«C:ДокументыКнига1.xlsx») = «» Then
MsgBox «File does not exist.»
EndIf
Проверьте открыта ли книга Смотрите раздел «Проверить
открыта ли книга»
Перечислите все открытые
рабочие книги
For Each wk In Application.Workbooks
Debug.Print wk.FullName
Next wk
Открыть книгу с помощью
диалогового окна «Файл»
Смотрите раздел «Использование диалогового окна «Файл»
Сохранить книгу wk.Save
Сохранить копию книги wk.SaveCopyAs «C:Копия.xlsm»
Скопируйте книгу, если она
закрыта
FileCopy «C:file1.xlsx»,»C:Копия.xlsx»
Сохранить как Рабочая книга wk.SaveAs «Резервная копия.xlsx»

Начало работы с книгой VBA

Мы можем получить доступ к любой открытой книге, используя код Workbooks («Пример.xlsm»). Просто замените Пример.xlsm именем книги, которую вы хотите использовать.

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

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

Первая часть до десятичной запятой представляет собой рабочую книгу, вторая часть представляет собой рабочую таблицу, а третья — диапазон. Вот еще несколько примеров записи в ячейку

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

Взгляните на часть книги

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

Устранение неполадок в коллекции книг

Когда вы используете коллекцию Workbooks для доступа к книге, вы можете получить сообщение об ошибке:

Run-time Error 9: Subscript out of Range.

Это означает, что VBA не может найти книгу, которую вы передали в качестве параметра.

Это может произойти по следующим причинам:

  1. Рабочая книга в настоящее время закрыта.
  2. Вы написали имя неправильно.
  3. Вы создали новую рабочую книгу (например, «Книга1») и попытались получить к ней доступ, используя Workbooks («Книга1.xlsx»). Это имя не Книга1.xlsx, пока оно не будет сохранено в первый раз.
  4. (Только для Excel 2007/2010) Если вы используете два экземпляра Excel, то Workbooks () относится только к рабочим книгам, открытым в текущем экземпляре Excel.
  5. Вы передали число в качестве индекса, и оно больше, чем количество открытых книг, например Вы использовали
    Workbooks (3), и только две рабочие книги открыты.

Если вы не можете устранить ошибку, воспользуйтесь любой из функций в разделе Поиск всех открытых рабочих книг. Они будут печатать имена всех открытых рабочих книг в «Immediate Window » (Ctrl + G).

Примеры использования рабочей книги VBA

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

Примечание. Чтобы попробовать этот пример, создайте две открытые книги с именами Тест1.xlsx и Тест2.xlsx.

Примечание: в примерах кода я часто использую Debug.Print. Эта функция печатает значения в Immediate Window. Для просмотра этого окна выберите View-> Immediate Window из меню (сочетание клавиш Ctrl + G)

Доступ к рабочей книге VBA по индексу

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

Workbooks (1) относится к книге, которая была открыта первой. Workbooks (2) относится к рабочей книге, которая была открыта второй и так далее.

В этом примере мы использовали Workbooks.Count. Это количество рабочих книг, которые в настоящее время находятся в коллекции рабочих книг. То есть количество рабочих книг, открытых на данный момент. Таким образом, использование его в качестве индекса дает нам последнюю книгу, которая была открыта

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

Поиск всех открытых рабочих книг

Иногда вы можете получить доступ ко всем рабочим книгам, которые открыты. Другими словами, все элементы в коллекции Workbooks ().

Вы можете сделать это, используя цикл For Each.

Вы также можете использовать стандартный цикл For для доступа ко всем открытым рабочим книгам.

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

Примечание. Оба примера читаются в порядке с первого открытого до последнего открытого. Если вы хотите читать в обратном порядке (с последнего на первое), вы можете сделать это

Открыть рабочую книгу

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

Следующий код VBA открывает книгу «Книга1.xlsm» в папке «C: Документы»

Рекомендуется проверить, действительно ли существует книга, прежде чем открывать ее. Это предотвратит ваши ошибки. Функция Dir позволяет вам легко это сделать.

Проверить открыта ли книга

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

Приведенную ниже функцию можно использовать для проверки, открыта ли книга в данный момент. Если нет, то откроется рабочая книга. В любом случае вы получите открытую рабочую книгу.

Вы можете использовать эту функцию так:

Этот код хорош в большинстве ситуаций. Однако, если рабочая книга может быть открыта в режиме только для чтения или может быть открыта в данный момент другим пользователем, возможно, вы захотите использовать немного другой подход.

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

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

Если вам нужно проверить, открыта ли книга в другом экземпляре Excel, вы можете использовать атрибут ReadOnly книги. Будет установлено значение true, если оно открыто в другом экземпляре.

Закрыть книгу

Закрыть книгу в Excel VBA очень просто. Вы просто вызываете метод Close рабочей книги.

Обычно, когда вы закрываете книгу в VBA, вы не хотите видеть сообщения из Excel, спрашивающие, хотите ли вы сохранить файл.

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

Очевидно, что вы не можете сохранить изменения в книге, которая в данный момент открыта только для чтения.

Сохранить книгу

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

Вы также можете использовать метод SaveAs

Метод WorkAs SaveAs поставляется с двенадцатью параметрами, которые позволяют вам добавить пароль, установить файл только для чтения и так далее. Вы можете увидеть детали здесь.

Вы также можете использовать VBA для сохранения книги в виде копии с помощью SaveCopyAs.

Копировать книгу

Если рабочая книга открыта, вы можете использовать два метода в приведенном выше разделе для создания копии, т.е. SaveAs и SaveCopyAs.

Если вы хотите скопировать книгу, не открывая ее, вы можете использовать FileCopy, как показано в следующем примере:

Использование диалогового окна «Файл» для открытия рабочей книги

В предыдущем разделе показано, как открыть книгу с заданным именем. Иногда вам может понадобиться, чтобы пользователь выбрал рабочую книгу. Вы можете легко использовать Windows File Dialog.

FileDialog настраивается, и вы можете использовать его так:

  1. Выберите файл.
  2. Выберите папку.
  3. Откройте файл.
  4. «Сохранить как» файл.

Если вы просто хотите, чтобы пользователь выбрал файл, вы можете использовать функцию GetOpenFilename.

Следующая функция открывает книгу с помощью диалога файлов. Функция возвращает полное имя файла, если файл был выбран. Если пользователь отменяет, он отображает сообщение и возвращает пустую строку.

Когда вы вызываете эту функцию, вы должны проверить, отменяет ли пользователь диалог.

В следующем примере показано, как легко вызвать функцию UserSelectWorkbook и обработать случай отмены пользователя.

Вы можете настроить диалог, изменив Title, Filters и AllowMultiSelect в функции UserSelectWorkbook.

Использование ThisWorkbook

Существует более простой способ доступа к текущей книге, чем использование Workbooks() . Вы можете использовать ключевое слово ThisWorkbook. Это относится к текущей книге, то есть к книге, содержащей код VBA.

Если наш код находится в книге, называемой МойVBA.xlsm, то ThisWorkbook и Workbooks («МойVBA.xlsm») ссылаются на одну и ту же книгу.

Использование ThisWorkbook более полезно, чем использование Workbooks (). С ThisWorkbook нам не нужно беспокоиться об имени файла. Это дает нам два преимущества:

  1. Изменение имени файла не повлияет на код
  2. Копирование кода в другую рабочую книгу не требует изменения кода

Это может показаться очень маленьким преимуществом. Реальность такова, что имена будут меняться все время. Использование ThisWorkbook означает, что ваш код будет работать нормально.

В следующем примере показаны две строки кода. Один с помощью ThisWorkbook, другой с помощью Workbooks (). Тот, который использует Workbooks, больше не будет работать, если имя МойVBA.xlsm изменится.

Использование ActiveWorkbook

ActiveWorkbook относится к книге, которая в данный момент активна. Это тот, который пользователь последний раз щелкнул.

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

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

Надеюсь, я дал понять, что вам следует избегать использования ActiveWorkbook, если в этом нет необходимости. Если вы должны быть очень осторожны.

Примеры доступа к книге

Мы рассмотрели все способы доступа к книге. Следующий код показывает примеры этих способов.

Объявление переменной VBA Workbook

Причина объявления переменной книги состоит в том, чтобы сделать ваш код более легким для чтения и понимания. Проще увидеть преимущество на примере:

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

Ниже показан тот же код без переменной рабочей книги.

В этих примерах разница несущественная. Однако, когда у вас много кода, использование переменной полезно, в частности, для рабочего листа и диапазонов, где имена имеют тенденцию быть длинными, например thisWorkbook.Worksheets («Лист1»). Range («A1»).

Вы можете назвать переменную книги как wrkRead или wrkWrite. Затем вы можете сразу увидеть, для чего используется эта книга.

Создать новую книгу

Для создания новой рабочей книги вы используете функцию добавления рабочих книг. Эта функция создает новую пустую книгу. Это то же самое, что выбрать «Новая книга» в меню «Файл Excel».

Когда вы создаете новую книгу, вы, как правило, хотите сохранить ее. Следующий код показывает вам, как это сделать.

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

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

With и Workbook

Ключевое слово With облегчает чтение и написание кода VBA. Использование с означает, что вам нужно упомянуть только один раз. С используется с объектами. Это такие элементы, как рабочие книги, рабочие таблицы и диапазоны.

В следующем примере есть два Subs. Первый похож на код, который мы видели до сих пор. Второй использует ключевое слово With. Вы можете увидеть код гораздо понятнее во втором Sub. Ключевые слова End With обозначают конец кода раздела с помощью With.

Резюме

Ниже приводится краткое изложение основных моментов этой статьи.

  1. Чтобы получить рабочую книгу, содержащую код, используйте ThisWorkbook.
  2. Чтобы получить любую открытую книгу, используйте Workbooks («Пример.xlsx»).
  3. Чтобы открыть книгу, используйте Set Wrk = Workbooks.Open («C: Папка Пример.xlsx»).
  4. Разрешить пользователю выбирать файл с помощью функции UserSelectWorkbook, представленной выше.
  5. Чтобы создать копию открытой книги, используйте свойство SaveAs с именем файла.
  6. Чтобы создать копию рабочей книги без открытия, используйте функцию FileCopy.
  7. Чтобы ваш код было легче читать и писать, используйте ключевое слово With.
  8. Другой способ прояснить ваш код — использовать переменные Workbook.
  9. Чтобы просмотреть все открытые рабочие книги, используйте For Every wk в Workbooks, где wk — это переменная рабочей книги.
  10. Старайтесь избегать использования ActiveWorkbook и Workbooks (Index), поскольку их ссылка на рабочую книгу носит временный характер.

Вы можете увидеть краткое руководство по теме в верхней части этой статьи

Заключение

Это был подробная статья об очень важном элементе VBA — Рабочей книги. Я надеюсь, что вы нашли ее полезной. Excel отлично справляется со многими способами выполнения подобных действий, но недостатком является то, что иногда он может привести к путанице.

Чтобы получить максимальную пользу от этой статьи, я рекомендую вам попробовать примеры. Создайте несколько книг и поиграйтесь с кодом. Внесите изменения в код и посмотрите, как эти изменения влияют на результат. Практика — лучший способ выучить VBA.

Источник

Понравилась статья? Поделить с друзьями:
  • Excel vba this file path
  • Excel vba this document
  • Excel vba this button
  • Excel vba textbox фокус на textbox
  • Excel vba textbox события