Vba excel this book

Home / VBA / VBA ThisWorkbook (Current Excel File)

In VBA, you can use the ThisWorkbook property to refer to the workbook where you are writing the code. When you use it, you get access to all the properties and methods of the current workbook. In simple words, you can execute all the tasks in the current workbook without using the name.

Let’s say you want to count the sheets from the current workbook. The code you need to write would be like the following.

Sub vba_thisworkbook()
MsgBox ThisWorkbook.Sheets.Count
End Sub
vba-thisworkbook

When you run this code shows you a message box with the count of the sheets that you have in the current workbook.

message-box-with-the-count-of-sheets

As I said, when you use the ThisWorkbook it gives you access to the properties and method for the current workbook. You can see all of these when you enter a (.) dot to see the complete list.

access-to-the-properties

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

Using ThisWorkbook with a Variable

Next, I’ll show you a real-life code example to declare a variable to use the ThisWorkbook property. Let’s say you want to perform multiple activities in the current workbook.

Sub vba_thisworkbook()
Dim myWB As Workbook
Set myWB = ThisWorkbook
With myWB
    .Activate
    .Sheets(1).Activate
    .Range("A1") = Now
    .Save
    .Close
End With
End Sub

In the first part of this code, you have a variable and then assign “ThisWorkbook” property to it. And then in the second part, you have the WITH STATEMENT to perform multiple activities with the current variable.

ActiveWorkBook Vs. ThisWorkbook

Let me explain it with a simple analogy, so, be with me for the next 2 minutes.

You have two workbooks open at the same time (Book1 and Book2). You are writing code in book1 but book2 is active at this point. So when you run that code which refers to the ActiveWorkbook it will perform that activity in Book2.

But when you use the ThisWorkbook VBA always refers to the workbook where code is being written.

Here’s the thing: It’s always preferable to use the ThisWorkbook because it eliminates the chances of any error.

More on VBA Workbooks

VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | 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

VBA ThisWorkbook means the workbook in which we are writing the Excel code. So, for example, if you are working in the workbook named “Sales 2019.xlsx,” we usually refer to the workbook like this.

Workbooks(“Sales 2019.xlsx”).Activate

The code will activate the workbook named “Sales 2019.xlsx”.

Instead of writing like this, we can simply write the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more below.

ThisWorkbook.Activate’

Here, ThisWorkbook refers to the workbook where we are writing the code. By referring to this word, we can execute all the tasks in the current workbook and avoid lengthy code with a fully named workbook name.

We are sure you must have also seen the word “Active Workbook” when referring to the other code. It is also one of the most often used words in coding. We will see what the differences between these two words in basic are.

Working with ThisWorkbook in Excel VBA

The reference word “ThisWorkbook” is more reliable than the Workbooks object qualifier. One human tendency is typing the workbook name wrongly, which results in an error message.

One more important reason why VBA ThisWorkbook is more reliable is that just in case we change the workbook name, we need to alter the code because we have used the word “ThisWorkbook.”

VBA-ThisWorkbook

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA ThisWorkbook (wallstreetmojo.com)

So, ThisWorkbook is safer to use for referring to the workbook where we are writing the code.

You can download this VBA ThisWorkbook Excel Template here – VBA ThisWorkbook Excel Template

Example #1

We will see examples of using the word ThisWorkbook in Excel VBA. The following code will print the workbook name.

Code:

Sub TWB_Example1()

    Dim WBName As String

    WBName = ThisWorkbook.Name

    MsgBox WBName

End Sub

VBA ThisWorkbook Example 1

When you run the code manually or using the F5 key, the above code will show the workbook name in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

VBA ThisWorkbook Example 1-2

Example #2

Instead of using the word “This Workbook,” we can use variables to set the workbook reference and even reduce the length of the code drastically in VBA. For example, look at the below code first.

Code:

Sub TWB_Example2()

ThisWorkbook.Activate
ThisWorkbook.Worksheets("Sheet1").Activate
ThisWorkbook.Save
ThisWorkbook.Close
ThisWorkbook.SaveAs

End Sub

Wb Example 2

The above code has used “ThisWorkbook” in every line of the code. How hard it is to type the word every time. So, we can minimize this by using variables.

Now, look at the below code with the variable.

Code:

Sub TWB_Example2()

  Dim Wb As Workbook
  
  Set Wb = ThisWorkbook

  Wb.Activate
  Wb.Worksheets("Sheet1").Activate
  Wb.Save
  Wb.Close
  Wb.SaveAs

End Sub

Wb Example 2-1

Looks beautiful, doesn’t it?

Let us explain the code.

First, we have declared the variable as a Workbook object.

Dim Wb As Workbook

Since this is an object variable, we need to set the reference to the particular workbook. So, we have used the “ThisWorkbook” reference.

Set Wb = ThisWorkbook

We reference the variable “Wb” in the workbook where we are currently writing the code. So, as we advance in the procedure, we need not use the word “ThisWorkbook”; instead, we can use the variable “Wb.”

Active Workbook vs. ThisWorkbook in Excel VBA

As we said at the beginning of the article, many coders use the words “Active Workbook” and “ThisWorkbook” very often in their VBA coding. However, it is difficult to understand these two as a reader or a new learner. So, let me explain to you some of the differences.

Difference #1: Meaning

  • Active Workbook: Active Workbook is not necessarily the workbook where we are currently writing the code. If you have multiple opened workbooks and the workbook is visible on your screen is considered an Active Workbook.
  • ThisWorkbook: ThisWorkbook is always the workbook where we are writing the code at the moment.

Difference 2: Error Chances

  • Active Workbook: Using Active in the coding may lead to many errors and confusion because we never know which workbook is active unless we specifically mention the workbook to activate before using the word Active Workbook.
  • ThisWorkbook: ThisWorkbook cannot go wrong because it does not matter which workbook is active. It always takes the reference of the workbook where we are writing the code.

Recommended Articles

This article is a guide to VBA ThisWorkbook. Here, we learn how to use ThisWorkbook as a reference in Excel VBA, with practical examples and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • VBA Workbook Open
  • Refresh Pivot Table in VBA
  • Print Labels From Excel
  • VBA Worksheets
title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.ThisWorkbook property (Excel)

vbaxl10.chm183111

vbaxl10.chm183111

excel

Excel.Application.ThisWorkbook

04b713dd-fd93-3cbc-f10b-05b9c3d107b1

04/05/2019

medium

Application.ThisWorkbook property (Excel)

Returns a Workbook object that represents the workbook where the current macro code is running. Read-only.

Syntax

expression.ThisWorkbook

expression A variable that represents an Application object.

Remarks

Use this property to refer to the workbook that contains your macro code. ThisWorkbook is the only way to refer to an add-in workbook from inside the add-in itself. The ActiveWorkbook property doesn’t return the add-in workbook; it returns the workbook that’s calling the add-in.

The Workbooks property may fail, as the workbook name probably changed when you created the add-in. ThisWorkbook always returns the workbook in which the code is running.

For example, use code such as the following to activate a dialog sheet stored in your add-in workbook:

ThisWorkbook.DialogSheets(1).Show

This property can be used only from inside Microsoft Excel. You cannot use it to access a workbook from any other application.

Example

This example closes the workbook that contains the example code. Changes to the workbook, if any, aren’t saved.

ThisWorkbook.Close SaveChanges:=False

[!includeSupport and feedback]

In this Article

  • ActiveWorkbook vs. ThisWorkbook
    • ThisWorkbook
    • ActiveWorkbook
  • VBA Assumes ActiveWorkbook
  • New or Opened Workbooks are Active
  • ThisWorkbook and ActiveWorkbook Examples
    • Switch Active Workbook
    • Make ThisWorkbook Active
    • Set ActiveWorkbook to a Variable
    • Close and Save the Active Workbook
    • Close the Active Workbook Without Saving
    • ActiveWorkbook – Save As

This tutorial will discuss the difference between the VBA ActiveWorkbook and ThisWorkbook objects.

ActiveWorkbook vs. ThisWorkbook

It’s important to the know the difference between the ActiveWorkbook and ThisWorkbook in VBA:

The ActiveWorkbook is the workbook that is currently active (similar to how ActiveSheet is the currently active sheet).  ThisWorkbook is the workbook where the VBA code is stored.  ThisWorkbook will never change.

ThisWorkbook

Think of ThisWorkbook as an object variable that allows you to reference the workbook containing the currently running code.

This code will display a MessageBox with ThisWorkbook name:

Sub Show_ThisWorkbook()
    MsgBox ThisWorkbook.Name
End Sub

vba thisworkbook activeworkbook

ActiveWorkbook

The ActiveWorkbook is an object variable that allows you to reference the currently active workbook.

This code will display a MessageBox with ActiveWorkbook name:

Sub Show_ActiveWorkbook()
    MsgBox ActiveWorkbook.Name
End Sub

VBA Assumes ActiveWorkbook

When attempting to work with objects (ex. Sheets) within the ActiveWorkbook, you do not need to explicitly state the ActiveWorkbook object. VBA will assume you are referring to the ActiveWorkbook.

So this:

ActiveWorkbook.Sheets("Sheet1").Range("$A$5").Value = 1

Is the same as this:

Sheets("Sheet1").Range("$A$5").Value = 1

New or Opened Workbooks are Active

Whenever you create a new workbook or open a workbook, the workbook becomes “Active”. You can see for yourself with this code that will add a workbook and retrieve the new workbook’s name:

Sub Show_ActiveWorkbook_Add()
    Workbooks.Add
    MsgBox ActiveWorkbook.Name
End Sub

After adding or opening a workbook, you can assign it to a variable by using the ActiveWorkbook object. We will show you how in the examples below:

ThisWorkbook and ActiveWorkbook Examples

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!

automacro

Learn More

Switch Active Workbook

Switch the active workbook using Workbook name:

Workbooks("Book1").Activate

Switch the active workbook using an index as a workbook order number (1 is the first workbook opened or created):

Workbooks(1).Activate

Make ThisWorkbook Active

Make ThisWorkbook (where the currently running code is stored) the ActiveWorkbook:

ThisWorkbook.Activate

Set ActiveWorkbook to a Variable

Assign the ActiveWorkbook to a workbook object variable:

Dim wb As Workbook
Set wb = ActiveWorkbook

VBA Programming | Code Generator does work for you!

Close and Save the Active Workbook

Closes and Saves the ActiveWorkbook:

ActiveWorkbook.Close SaveChanges:=True

Close the Active Workbook Without Saving

Closes the ActiveWorkbook without saving:

ActiveWorkbook.Close SaveChanges:=False

ActiveWorkbook – Save As

Performs a Save As of the active Workbook.

Sub SaveAsActiveWorkbook()
    Dim result As Variant
    result = Application.GetSaveAsFilename(InitialFileName:="", _
    FileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm,Excel Workbook (*.xlsx), *.xlsx")
    
    If result = False Then Exit Sub
    
    ActiveWorkbook.SaveAs result
End Sub

Содержание

  1. Workbook object (Excel)
  2. Remarks
  3. Example
  4. Events
  5. Methods
  6. Properties
  7. See also
  8. Support and feedback
  9. Свойство Application.ThisWorkbook (Excel)
  10. Синтаксис
  11. Примечания
  12. Пример
  13. Поддержка и обратная связь
  14. Application.ThisWorkbook property (Excel)
  15. Syntax
  16. Remarks
  17. Example
  18. Support and feedback
  19. Name already in use
  20. VBA-Docs / api / Excel.Application.ThisWorkbook.md
  21. VBA ActiveWorkbook vs. ThisWorkbook
  22. ActiveWorkbook vs. ThisWorkbook
  23. ThisWorkbook
  24. ActiveWorkbook
  25. VBA Assumes ActiveWorkbook
  26. New or Opened Workbooks are Active
  27. ThisWorkbook and ActiveWorkbook Examples
  28. VBA Coding Made Easy
  29. Switch Active Workbook
  30. Make ThisWorkbook Active
  31. Set ActiveWorkbook to a Variable
  32. Close and Save the Active Workbook
  33. Close the Active Workbook Without Saving
  34. ActiveWorkbook – Save As
  35. VBA Code Examples Add-in

Workbook object (Excel)

Represents a Microsoft Excel workbook.

The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel.

The ThisWorkbook property of the Application object returns the workbook where the Visual Basic code is running. In most cases, this is the same as the active workbook. However, if the Visual Basic code is part of an add-in, the ThisWorkbook property won’t return the active workbook. In this case, the active workbook is the workbook calling the add-in, whereas the ThisWorkbook property returns the add-in workbook.

If you are creating an add-in from your Visual Basic code, you should use the ThisWorkbook property to qualify any statement that must be run on the workbook that you compile into the add-in.

Example

Use Workbooks (index), where index is the workbook name or index number, to return a single Workbook object. The following example activates workbook one.

The index number denotes the order in which the workbooks were opened or created. Workbooks(1) is the first workbook created, and Workbooks(Workbooks.Count) is the last one created. Activating a workbook doesn’t change its index number. All workbooks are included in the index count, even if they are hidden.

The Name property returns the workbook name. You cannot set the name by using this property; if you need to change the name, use the SaveAs method to save the workbook under a different name.

The following example activates Sheet1 in the workbook named Cogs.xls (the workbook must already be open in Microsoft Excel).

The ActiveWorkbook property of the Application object returns the workbook that’s currently active. The following example sets the name of the author for the active workbook.

This example emails a worksheet tab from the active workbook by using a specified email address and subject. To run this code, the active worksheet must contain the email address in cell A1, the subject in cell B1, and the name of the worksheet to send in cell C1.

Events

Methods

Properties

See also

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.

Источник

Свойство Application.ThisWorkbook (Excel)

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

Синтаксис

expression. Thisworkbook

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

Примечания

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

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

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

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

Пример

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

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

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

Источник

Application.ThisWorkbook property (Excel)

Returns a Workbook object that represents the workbook where the current macro code is running. Read-only.

Syntax

expression.ThisWorkbook

expression A variable that represents an Application object.

Use this property to refer to the workbook that contains your macro code. ThisWorkbook is the only way to refer to an add-in workbook from inside the add-in itself. The ActiveWorkbook property doesn’t return the add-in workbook; it returns the workbook that’s calling the add-in.

The Workbooks property may fail, as the workbook name probably changed when you created the add-in. ThisWorkbook always returns the workbook in which the code is running.

For example, use code such as the following to activate a dialog sheet stored in your add-in workbook:

This property can be used only from inside Microsoft Excel. You cannot use it to access a workbook from any other application.

Example

This example closes the workbook that contains the example code. Changes to the workbook, if any, aren’t saved.

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.

Источник

Name already in use

VBA-Docs / api / Excel.Application.ThisWorkbook.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Application.ThisWorkbook property (Excel)

Returns a Workbook object that represents the workbook where the current macro code is running. Read-only.

expression.ThisWorkbook

expression A variable that represents an Application object.

Use this property to refer to the workbook that contains your macro code. ThisWorkbook is the only way to refer to an add-in workbook from inside the add-in itself. The ActiveWorkbook property doesn’t return the add-in workbook; it returns the workbook that’s calling the add-in.

The Workbooks property may fail, as the workbook name probably changed when you created the add-in. ThisWorkbook always returns the workbook in which the code is running.

For example, use code such as the following to activate a dialog sheet stored in your add-in workbook:

This property can be used only from inside Microsoft Excel. You cannot use it to access a workbook from any other application.

This example closes the workbook that contains the example code. Changes to the workbook, if any, aren’t saved.

Источник

VBA ActiveWorkbook vs. ThisWorkbook

In this Article

This tutorial will discuss the difference between the VBA ActiveWorkbook and ThisWorkbook objects.

ActiveWorkbook vs. ThisWorkbook

It’s important to the know the difference between the ActiveWorkbook and ThisWorkbook in VBA:

The ActiveWorkbook is the workbook that is currently active (similar to how ActiveSheet is the currently active sheet). ThisWorkbook is the workbook where the VBA code is stored. ThisWorkbook will never change.

ThisWorkbook

Think of ThisWorkbook as an object variable that allows you to reference the workbook containing the currently running code.

This code will display a MessageBox with ThisWorkbook name:

ActiveWorkbook

The ActiveWorkbook is an object variable that allows you to reference the currently active workbook.

This code will display a MessageBox with ActiveWorkbook name:

VBA Assumes ActiveWorkbook

When attempting to work with objects (ex. Sheets) within the ActiveWorkbook, you do not need to explicitly state the ActiveWorkbook object. VBA will assume you are referring to the ActiveWorkbook.

Is the same as this:

New or Opened Workbooks are Active

Whenever you create a new workbook or open a workbook, the workbook becomes “Active”. You can see for yourself with this code that will add a workbook and retrieve the new workbook’s name:

After adding or opening a workbook, you can assign it to a variable by using the ActiveWorkbook object. We will show you how in the examples below:

ThisWorkbook and ActiveWorkbook Examples

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!

Switch Active Workbook

Switch the active workbook using Workbook name:

Switch the active workbook using an index as a workbook order number (1 is the first workbook opened or created):

Make ThisWorkbook Active

Make ThisWorkbook (where the currently running code is stored) the ActiveWorkbook:

Set ActiveWorkbook to a Variable

Assign the ActiveWorkbook to a workbook object variable:

Close and Save the Active Workbook

Closes and Saves the ActiveWorkbook:

Close the Active Workbook Without Saving

Closes the ActiveWorkbook without saving:

ActiveWorkbook – Save As

Performs a Save As of the active Workbook.

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 vs ThisWorkbook

ThisWorkbook refers to the workbook in which Excel VBA code is being executed. ActiveWorkbook on the other hand refers to the Excel Workbook that current has focus, meaning is the front facing Excel Window.

Often Excel VBA Developers mix these two common types of Workbooks in VBA. The problem starts to arise when you work in multiple Excel Workbooks at the same time and by accident run a macro from a Workbook while another Excel Workbook is currently active. This may have disastrous effects if you use VBA Range or VBA Cell properties directly.

In this article let me explain the distinct difference between the Excel VBA ActiveWorkbook vs ThisWorkbook objects.

The ActiveWorkbook is not just the visible Workbook as many would think, as you can just as well have multiple Workbooks open and placed side by side. However, only one Excel Workbook is considered Active in any point in time. Being Active is a top-most property – only the Workbook who’s window is currently selected is considered Active. See below for a precise definition

Application.ActiveWorkbook or ActiveWorkbook in Excel VBA:
Will return the Workbook object that represents the workbook in the active window (the window on top). The property will return Nothing if the Info window or the Clipboard window is the active window.

Excel VBA ActiveWorkbook example

'Returns the name of the Active Workbook in Excel VBA
Debug.Print ActiveWorkbook.Name

'Get Sheet1 from the Active Workbook
ActiveWorkbook.Sheets("Sheet1")

ThisWorkbook

The ThisWorkbook property is much easier to understand as it simply references the Excel Workbook in which the VBA code is executing. For the full definition see below:

Application.ThisWorkbook or ThisWorkbook in Excel VBA:
Will return the Workbook object that represents the workbook where the current VBA macro code is running.

Excel VBA ThisWorkbook example

'Returns the name of the Workbook which is executing this Macro
Debug.Print ActiveWorkbook.Name

'Get Sheet1 from the Workbook executing this Macro
ActiveWorkbook.Sheets("Sheet1")

ActiveWorkbook vs ThisWorkbook

If you are still confused about the difference between these two properties see below:
ActiveWorkbook vs ThisWorkbook
On the left the Excel Workbook is visible and is the foremost application. In this case if you run a macro in this Workbook the ActiveWorkbook property is the same as ThisWorkbook.

On the right the Excel Workbook is not visible or is not the foremost application. In this case if you run a macro in this Workbook the ActiveWorkbook property represents the Workbook on the left, and ThisWorkbook represents the Workbook on the right.

Hope that’s clear now!

Conclusions

Now that you can distinguish between both these properties it is important to keep a couple of things in mind:

  • On a daily basis use ThisWorkbook over the more erroneous ActiveWorkbook, when you expect your code to run on the same Workbook you are working on
  • Use ActiveWorkbook carefully, as it is a top-most property it might not always return a property if other Excel pop-up windows will be involved. Although you might need the ActiveWorkbook property when working with Excel AddIns (which execute code on the Active Workbook not your AddIn)

Referencing workbooks and sheets programmatically generates a lot of confusion because there are so many possibilities. No method is superior; they all have their place. The purpose at hand will define which referencing method is the most efficient.

Note: This article is also available as a PDF download.

1: Reference the active workbook

VBA’s ActiveWorkbook property refers to the workbook with the focus. The active workbook may or may not contain the code that’s referencing the active workbook, which is an important distinction. It’s perfectly acceptable to use this property to reference the active workbook from code inside the active workbook. However, it’s invaluable when referencing the active workbook remotely.

For example, after passing data to an active workbook, you’d probably want to save that workbook, which is a simple task for the ActiveWorkbook property. The following procedures use the ActiveWorkbook property to close the active workbook:

Sub CloseActiveWBNoSave() <p> 'Close the active workbook without saving.</p> <p> ActiveWorkbook.Close False</p> End Sub
Sub CloseActiveWBWithSave() <p> 'Close the active workbook and save.</p> <p> ActiveWorkbook.Close True</p> End Sub
Sub CloseActiveWB() <p> 'Close the active workbook.</p> <p> 'Let user choose whether to save.</p> <p> ActiveWorkbook.Close</p> End Sub

Of course, you could just as easily combine all three into a Select Case statement and use a single function to pass a conditional argument that specifies which save to execute.

LEARN MORE: Office 365 Consumer pricing and features

Figure A

Function GetActiveWB() As String <p> GetActiveWB = ActiveWorkbook.Path & "" & ActiveWorkbook.Name</p> End Function

Figure A

Use the ActiveWorkbook property to return the active workbook’s full path and filename.

2: Reference the workbook that’s currently running code

VBA’s ThisWorkbook property is similar to the ActiveWorkbook property, but whereas ActiveWorkbook evaluates the workbook with the focus, ThisWorkbook refers to the workbook that’s running the current code. This added flexibility is great because the active workbook isn’t always the workbook that’s running code.

Figure B

Function GetThisWB() As String <p> GetThisWB = ThisWorkbook.Path & "" & ThisWorkbook.Name</p> End Function

As you can see, HumanResources.xls is the active workbook, but the function is in a workbook named 0908002.xls.

Figure B

Take advantage of ThisWorkbook’s flexibility when you need to refer to the workbook running code when the active workbook isn’t the workbook running code.

3: Reference workbooks in the Workbooks collection

The Workbooks collection contains all the open Workbook objects. Using the Workbooks property, you can refer to open workbooks. For instance, the following subprocedure populates a list box in a user form with the names of all open workbooks:

Private Sub UserForm_Activate() <p> 'Populate list box with names of open workbooks.</p> <p> Dim wb As Workbook</p> <p> For Each wb In Workbooks</p> <p> ListBox1.AddItem wb.Name</p> <p> Next wb</p> End Sub

The resulting user form, shown in Figure C, displays a list of open workbooks. By referencing the Workbooks collection, you can reference all the open workbooks without hard-coding a single workbook name.

Figure C

Use the Workbooks collection to reference open workbooks.

Listing all the open workbooks is an easy enough task, thanks to the Workbooks collection. However, opening all of the workbooks in a specified folder is a bit harder, as you can see in the following subprocedure:

Sub OpenAllWB() <p> 'Open all workbooks in specified folder.</p> <p> Dim i As Integer</p> <p> With Application.FileSearch</p> <p> .LookIn = "C:Examples"</p> <p> .FileType = msoFileTypeExcelWorkbooks</p> <p> 'There are wb's</p> <p> If .Execute > 0 Then</p> <p> For i = 1 To .FoundFiles.Count</p> <p> Workbooks.Open (.FoundFiles(i))</p> <p> Next i</p> <p> 'There are no wb's</p> <p> Else</p> <p> MsgBox "There are no workbooks to open", vbOKOnly</p> <p> End If</p> <p> End With</p> End Sub

This task isn’t a referencing one in the true sense, but it shows the power of the Workbooks collection. In this case, the code doesn’t cycle through the Workbooks collection; it just takes advantage of one of the collection’s methods — specifically, the Open method. Closing all the open workbooks is a bit easier than opening them, as the following procedure shows:

Sub CloseAllWB() <p> 'Close all open workbooks.</p> <p> Workbooks.Close</p> End Sub

To see a collection’s many methods and properties, press F2 in the VBE to launch the Object Browser.

4: Explicitly reference a workbook

If you know the name of the workbook you want to reference, an explicit reference might be the most efficient method. Although an explicit reference is easy, it does require a stable situation. If the name of the workbook changes, but the possibilities are known, you can still use an explicit reference by passing the workbook’s name. For example, the following subprocedure activates an open workbook, as determined by the passed argument, wbname:

Function ActivateWB(wbname As String) <p> 'Open wbname.</p> <p> Workbooks(wbname).Activate</p> End Function

To execute it, you simply pass the name of the workbook you want to activate as follows:

ActivateWB("HumanResources.xls")

(You must include the .xls extension.)

The following function also uses the Workbooks property to determine whether a specific workbook is currently open:

Function IsWBOpen(wbname As String) As Boolean <p> 'Open workbook.</p> <p> Dim wb As Workbook</p> <p> On Error Resume Next</p> <p> Set wb = Workbooks(wbname)</p> <p> IsWBOpen = Not wb Is Nothing</p> End Function

If wbname is open, the function returns True. When not open, the function returns False. These procedures also rely on the Workbooks property, but instead of cycling through the collection, they specify a workbook by name.

5: Reference workbooks by index

Perhaps the least stable method for referencing a workbook is to use its index value. Excel assigns index values to workbooks as you open them. The first workbook opened has an index value of 1, the second workbook opened has an index value of 2, and so on.

Index values pose a special problem because they change when you delete a Workbook object from the collection; index values slip down a notch, accordingly. For example, suppose you have three open workbooks with the following index values:

ExcelStatisticalFunctions — 3

0908002.xls – 2

HumanResources.xls – 1

If a particular task depends on all three workbooks always being open, using the index values can generate mistakes. For instance, the statement

Workbooks(1).Activate

activates HumanResources.xls as long as it’s open. If you close HumanResources.xls, ExcelStatisticalFunctions and 0908002.xls both move down a notch: ExcelStatisticalFunctions becomes 2 and 0908002.xls becomes 1. As a result, the above statement activates 0908002.xls, not HumanResources. That may or may not be what you want. Using index values to reference workbooks isn’t wrong, but you must understand its inherent behaviors to avoid errors that can be difficult to troubleshoot.

6: Reference the active sheet

If you don’t specify an object qualifier, the ActiveSheet property defaults to the active sheet in the active workbook. For instance, to retrieve the name of the active sheet, you’d use a function similar to the following:

Function GetActiveSheet() As String <p> GetActiveSheet = ActiveSheet.Name</p> End Function

This property is read-only; you can’t use it to activate a sheet.

7: Reference Worksheet objects

The Worksheets collection contains all the sheet objects in a workbook. Using a simple For Each loop, you can cycle through the collection. For example, the following code populates a list box control with the names of all the sheets in the active workbook:

Private Sub UserForm_Activate() <p> 'Populate list box with names of sheets</p> <p> 'in active workbook.</p> <p> Dim ws As Worksheet</p> <p> For Each ws In Worksheets</p> <p> ws.Select</p> <p> ListBox1.AddItem ws.Name</p> <p> Next ws</p> End Sub

The Sheets and Worksheets collections both contain Worksheet objects, but the Sheets collection contains both worksheets and chart sheets.

8: Explicitly reference sheets

Use the Worksheets property to explicitly reference a sheet. For example, use this type of reference to delete a specific sheet as follows:

Function DeleteSheet(shtname As String) <p> 'Delete shtname.</p> <p> Application.DisplayAlerts = False</p> <p> Worksheets(shtname).Delete</p> <p> Application.DisplayAlerts = True</p> End Function

9: Reference sheets by index

Index values come in handy when you don’t care about specific sheets, but only their number or order. Granted, that’s not going to be a common task, but occasionally, referencing by index values can come in handy. The following procedure adds and deletes sheets based on the number of sheets you want:

Function ControlSheetNumber(intSheets As Integer) <p> 'Add or delete sheets to equal intSheets.</p> <p> Application.DisplayAlerts = False</p> <p> 'Delete sheets if necessary</p> <p> While Worksheets.Count > intSheets</p> <p> Worksheets(1).Delete</p> <p> Wend</p> <p> 'Add sheets if necessary</p> <p> While Worksheets.Count < intSheets</p> <p> Worksheets.Add</p> <p> Wend</p> <p> Application.DisplayAlerts = True</p> End Function

Use caution when executing this function because it deletes the first Sheet object in the collection, even if that sheet contains content. It simply adds and deletes sheets, depending on the value you pass. This function is useful when creating new workbooks programmatically.

10: Refer to a sheet’s code name property

Code that refers to a Worksheet object by the name on the sheet’s tab runs the risk of generating an error. That’s because you must remember to update the code when you change the sheet’s name. Not only is that a lot of trouble, users are apt to change a sheet’s name. One way to safeguard code that refers to specific sheets by name is to use the CodeName property.

The code name is the sheet’s default name , which Excel assigns when you create it — Sheet1, Sheet2, and so on. Changing the sheet’s name, as displayed on the sheet’s tab, does not change its code name, as you can see in Figure D. The names in parentheses are the sheet names (as shown on the sheet tabs). Notice that the default names, the code names, remain the same even if you change the sheet’s name.

Figure D

A sheet’s code name property is stable; its sheet name is subject to change.

To change a sheet’s code name, use the (Name) property, as shown in Figure E. You must use the Visual Basic Editor (VBE), as you can’t change this property programmatically. There are two similar properties, so don’t confuse them. The Name property (without parentheses) toward the bottom of the properties list represents the name Excel displays on the sheet tab. (Code name values must start with a letter character.)

Figure E

Change the code name using the VBE.

Also see

  • How to add a drop-down list to an Excel cell (TechRepublic)
  • How to become a cloud engineer: A cheat sheet (TechRepublic)
  • 50 time-saving tips to speed your work in Microsoft Office (free PDF) (TechRepublic download)
  • Cost comparison calculator: G Suite vs. Office 365 (Tech Pro Research)
  • Microsoft Office has changed, how you use it should too (ZDNet)
  • Best cloud services for small businesses (CNET)
  • Best to-do list apps for managing tasks on any platform (Download.com)
  • More must-read Microsoft-related coverage (TechRepublic on Flipboard)

Affiliate disclosure: TechRepublic may earn a commission from the products and services featured on this page.

Понравилась статья? Поделить с друзьями:
  • Vba excel then do the
  • Vba excel textbox форматы
  • Vba excel textbox формат даты
  • Vba excel textbox только числа
  • Vba excel textbox проверка