[Excel VBA] How to Add a New Workbook and Control It Reliably Using Object Variables

目次

Introduction

Aggregating data in VBA and saving the results to a new workbook is a very common task. However, developers often face a problem: “I created a new workbook using Workbooks.Add, but how do I control that specific workbook accurately?”

In this article, I will explain the most important and basic method for reliably controlling a newly created workbook by storing it in an “Object Variable”.

Why Use Object Variables?

When you execute Workbooks.Add in VBA, a new workbook named “Book1” or “Book2” is created. However, this name changes depending on the situation, so you cannot rely on it.

Many beginners write code like this:

' Bad Example: Unstable Code
Workbooks.Add
ActiveWorkbook.SaveAs "C:\temp\test.xlsx" 
' Risk: If the user clicks another workbook while this runs, 
' the wrong workbook might be saved!

To eliminate this instability and control “the specific workbook I just made” directly, we use object variables. Since the Workbooks.Add method returns the object of the created workbook, we use a variable as a container to catch it.

Complete VBA Code

Below is the complete code. It creates a new workbook, uses an object variable to enter data, saves it, and closes it.

Sub CreateAndManageNewWorkbook()

    ' Declare a variable to hold the Workbook object
    Dim newBook As Workbook
    
    ' --- 1. Add a new workbook and store its object in the variable ---
    ' Workbooks.Add returns the "new workbook," so we Set it to newBook
    Set newBook = Workbooks.Add
    
    ' --- 2. Control the new workbook using the object variable ---
    ' Check the name of the new workbook
    MsgBox "Created new workbook: " & newBook.Name
    
    ' Enter a value in cell A1 of the first sheet of the new workbook
    newBook.Worksheets(1).Range("A1").Value = "This book was created by VBA."
    
    ' --- 3. Save and close the new workbook ---
    ' Save with a specific filename in the same folder as this macro
    newBook.SaveAs Filename:=ThisWorkbook.Path & "\New_VBA_Report.xlsx"
    
    ' Close the workbook after saving
    newBook.Close
    
    ' --- 4. Release the object variable ---
    Set newBook = Nothing
    
    MsgBox "Created, saved, and closed the new workbook."

End Sub

Key Points of the Code

1. Dim ... As Workbook

Dim newBook As Workbook

First, declare a variable with the Workbook type. By explicitly stating As Workbook, VBA understands that “this variable will hold workbook information.” This helps with development, as it enables features like IntelliSense (auto-completion).

2. Set newBook = Workbooks.Add

Set newBook = Workbooks.Add

This is the core of this technique.

  1. Workbooks.Add is executed, creating a new workbook.
  2. Workbooks.Add returns the object of the created workbook as a return value.
  3. We use the Set keyword to assign that object to the newBook variable.

From this point on, the variable newBook refers directly to the newly created workbook.

3. Operations Using newBook

newBook.Worksheets(1).Range("A1").Value = "..."
newBook.SaveAs ...
newBook.Close

Once you store the workbook in the newBook variable, you can manipulate it directly using that name. You do not need to use ambiguous commands like ActiveWorkbook.

Even if other workbooks are open, or if the user clicks a different window during the process, your code will always target the correct workbook.

Summary

When creating a new object (Workbook, Worksheet, Shape, etc.) in VBA, always follow the “Iron Rule” of using the Set keyword to keep a reference to it:

Set myObject = ParentObject.Add

By strictly following this basic pattern, you gain two major benefits:

  1. Reliability: You create stable macros that are not affected by user actions or other open files.
  2. Readability: Anyone reading the code can strictly understand which object is being manipulated.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次