Return to VBA Code Examples
This tutorial will demonstrate how to get and set the Workbook name in VBA.
We can get or set the name of the Active workbook in VBA, or loop through all the open workbooks in Excel, and get or set the name of each of them using a VBA Loop.
Get Workbook Name
To get the name of the active workbook, we need to use the name property of the workbooks object.
Sub GetWorkbookName()
Dim strWBName As String
strWBName = ActiveWorkbook.Name
MsgBox strWBName
End Sub
If we were to run the code above, we would see a message box appear on the screen with the name of the Active workbook.
To loop through all the active Workbooks, and return the names of the workbooks to Excel, we can run the following code:
Sub GetWorkbookNames()
Dim wb As Workbook
For Each wb In Workbooks
ActiveCell = wb.Name
ActiveCell.Offset(1, 0).Select
Next
End Sub
The examples above will include the extension of the file (eg xlsx). If you do not want to include the extension, there are a few methods we can use to obtain just the filename of the workbook.
Get Workbook Name Without Extension
We can use the LEFT and INSTR functions to remove any characters after the period in the file name:
Sub GetWorkbookName()
Dim strWBName As String
strWBName = Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1)
MsgBox strWBName
End Sub
We can use the LEFT and LEN functions to remove 5 characters from the end of the file name:
Sub GetWorkbookName()
Dim strWBName As String
strWBName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 55)
MsgBox strWBName
End Sub
Setting the Workbook Name
To set the name of a workbook in VBA, we still use the Name property of the workbook, however we cannot use this method to change the name of the Active Workbook. This is due to the fact that the Active workbook is open, and a file access error will occur. To overcome this, we can save the file with a new name and then delete the old file.
Public Sub SetWorkbookName()
Dim strPath As String
Dim strNewName As String
Dim strOldName As String
strOldName = ActiveWorkbook.Name
strNewName = InputBox("Please enter new name for workbook")
strPath = ActiveWorkbook.Path
ActiveWorkbook.SaveAs strPath & "/" & strNewName
Kill strPath & "/" & strOldName
End Sub
To rename a workbook that is not open, we can use the Name method.
Public Sub RenameWorkbook()
Name "C:DataMyFile.xlsx" As "C:DataMyNewFile.xlsx"
End Sub
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!
Learn More!
VBA Get Workbook Name in Excel. We can return workbook name using Workbook.Name property. Here workbook represents an object. It is part of Workbooks collection. Returns a string value representing Workbook name. We can find Active Workbook or Current Workbook name using Name property of Workbook.
Table of Contents:
- Overview
- Syntax to return Name of the Workbook VBA in Excel
- Get Name of the Active Workbook using VBA in Excel
- Macro to Get Current Workbook Name using VBA in Excel
- Instructions to Run VBA Macro Code
- Other Useful Resources
Syntax to get current Workbook name using VBA in Excel
Here is the following syntax to get the Name of the Workbook using VBA in Excel.
expression.Name
Where expression: It represents Workbook object which is part of workbooks collection.
Name: It represents property of Workbook object to get Workbook name.
Get Name of the Active Workbook using VBA in Excel
Let us see the following example macro to get current or active workbook name in using VBA in Excel. Where ‘Name’ represents the property of Workbook object. It helps to get the name of the Workbook.
'Get Active Workbook name in Excel using VBA Sub VBA_Get_ActiveWorkbook_Name() 'Variable declaration Dim sActiveWorkbookName As String sActiveWorkbookName = ActiveWorkbook.Name End Sub
Output: Please find the output screenshot of the above macro code.
Macro to Get Current Workbook Name using VBA in Excel
Here is another example macro code to get current workbook name using VBA in Excel.
'Get current workbook name of the Workbook using VBA in Excel Sub VBA_Get_CurrentWorkbook_Name() 'Variable declaration Dim sCurrentWorkbookName As String sCurrentWorkbookName = ThisWorkbook.Name End Sub
Output: Here is the output screenshot of the above macro code.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions to execute VBA code or procedure.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
Содержание
- Объект Names (Excel)
- Замечания
- Пример
- Методы
- Свойства
- См. также
- Поддержка и обратная связь
- Names object (Excel)
- Remarks
- Example
- Methods
- Properties
- See also
- Support and feedback
- Workbook object (Excel)
- Remarks
- Example
- Events
- Methods
- Properties
- See also
- Support and feedback
- VBA Get Workbook Name in Excel
- Syntax to get current Workbook name using VBA in Excel
- Get Name of the Active Workbook using VBA in Excel
- Macro to Get Current Workbook Name using VBA in Excel
- Instructions to Run VBA Macro Code or Procedure:
- Other Useful Resources:
- VBA Workbook Name (Get, Set, without Extension)
- Get Workbook Name
- Get Workbook Name Without Extension
- Setting the Workbook Name
- VBA Coding Made Easy
- VBA Code Examples Add-in
Объект Names (Excel)
Коллекция всех объектов Name в приложении или книге.
Замечания
Каждый объект Name представляет определенное имя для диапазона ячеек. Имена могут быть встроенными именами, например базами данных, Print_Area и Auto_Open, или пользовательскими именами.
Аргумент RefersTo должен быть указан в нотации в стиле A1, включая знаки доллара ($) при необходимости. Например, если ячейка A10 выбрана на листе Лист1 и вы определяете имя с помощью аргумента RefersTo «=лист1! A1:B1», новое имя фактически относится к ячейкам A10:B10 (так как вы указали относительную ссылку). Чтобы указать абсолютную ссылку, используйте «=лист1!$A$1:$B$1».
Пример
Используйте свойство Names объекта Workbook , чтобы вернуть коллекцию Names . В следующем примере создается список всех имен в активной книге, а также адресов, на которые они ссылаются.
Используйте метод Add , чтобы создать имя и добавить его в коллекцию. В следующем примере создается новое имя, которое ссылается на ячейки A1:C20 на листе с именем Sheet1.
Используйте name (index), где index — это номер индекса имени или определенное имя, чтобы вернуть один объект Name . В следующем примере имя mySortRange удаляется из активной книги.
В этом примере в качестве формулы для проверки данных используется именованный диапазон. В этом примере данные проверки должны быть на листе 2 в диапазоне A2:A100. Эти данные проверки используются для проверки данных, введенных на листе Sheet1 в диапазоне D2:D10.
Методы
Свойства
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Names object (Excel)
A collection of all the Name objects in the application or workbook.
Each Name object represents a defined name for a range of cells. Names can be either built-in names—such as Database, Print_Area, and Auto_Open—or custom names.
The RefersTo argument must be specified in A1-style notation, including dollar signs ($) where appropriate. For example, if cell A10 is selected on Sheet1 and you define a name by using the RefersTo argument «=sheet1!A1:B1», the new name actually refers to cells A10:B10 (because you specified a relative reference). To specify an absolute reference, use «=sheet1!$A$1:$B$1».
Example
Use the Names property of the Workbook object to return the Names collection. The following example creates a list of all the names in the active workbook, plus the addresses that they refer to.
Use the Add method to create a name and add it to the collection. The following example creates a new name that refers to cells A1:C20 on the worksheet named Sheet1.
Use Names (index), where index is the name index number or defined name, to return a single Name object. The following example deletes the name mySortRange from the active workbook.
This example uses a named range as the formula for data validation. This example requires the validation data to be on Sheet 2 in the range A2:A100. This validation data is used to validate data entered on Sheet1 in the range D2:D10.
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.
Источник
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.
Источник
VBA Get Workbook Name in Excel
VBA Get Workbook Name in Excel. We can return workbook name using Workbook.Name property. Here workbook represents an object. It is part of Workbooks collection. Returns a string value representing Workbook name. We can find Active Workbook or Current Workbook name using Name property of Workbook.
Syntax to get current Workbook name using VBA in Excel
Here is the following syntax to get the Name of the Workbook using VBA in Excel.
Where expression: It represents Workbook object which is part of workbooks collection.
Name: It represents property of Workbook object to get Workbook name.
Get Name of the Active Workbook using VBA in Excel
Let us see the following example macro to get current or active workbook name in using VBA in Excel. Where ‘Name’ represents the property of Workbook object. It helps to get the name of the Workbook.
Output: Please find the output screenshot of the above macro code.
Active Workbook Name
Macro to Get Current Workbook Name using VBA in Excel
Here is another example macro code to get current workbook name using VBA in Excel.
Output: Here is the output screenshot of the above macro code.
This Workbook Name
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions to execute VBA code or procedure.
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
Источник
VBA Workbook Name (Get, Set, without Extension)
In this Article
This tutorial will demonstrate how to get and set the Workbook name in VBA.
We can get or set the name of the Active workbook in VBA, or loop through all the open workbooks in Excel, and get or set the name of each of them using a VBA Loop.
Get Workbook Name
To get the name of the active workbook, we need to use the name property of the workbooks object.
If we were to run the code above, we would see a message box appear on the screen with the name of the Active workbook.
To loop through all the active Workbooks, and return the names of the workbooks to Excel, we can run the following code:
The examples above will include the extension of the file (eg xlsx). If you do not want to include the extension, there are a few methods we can use to obtain just the filename of the workbook.
Get Workbook Name Without Extension
We can use the LEFT and INSTR functions to remove any characters after the period in the file name:
We can use the LEFT and LEN functions to remove 5 characters from the end of the file name:
Setting the Workbook Name
To set the name of a workbook in VBA, we still use the Name property of the workbook, however we cannot use this method to change the name of the Active Workbook. This is due to the fact that the Active workbook is open, and a file access error will occur. To overcome this, we can save the file with a new name and then delete the old file.
To rename a workbook that is not open, we can use the Name method.
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!
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.
Источник
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Names object (Excel) |
vbaxl10.chm487072 |
vbaxl10.chm487072 |
excel |
Excel.Names |
ffecf89d-7bae-c470-8e37-608857a9de2a |
03/30/2019 |
medium |
Names object (Excel)
A collection of all the Name objects in the application or workbook.
Remarks
Each Name object represents a defined name for a range of cells. Names can be either built-in names—such as Database, Print_Area, and Auto_Open—or custom names.
The RefersTo argument must be specified in A1-style notation, including dollar signs ($) where appropriate. For example, if cell A10 is selected on Sheet1 and you define a name by using the RefersTo argument «=sheet1!A1:B1», the new name actually refers to cells A10:B10 (because you specified a relative reference). To specify an absolute reference, use «=sheet1!$A$1:$B$1».
Example
Use the Names property of the Workbook object to return the Names collection. The following example creates a list of all the names in the active workbook, plus the addresses that they refer to.
Set nms = ActiveWorkbook.Names Set wks = Worksheets(1) For r = 1 To nms.Count wks.Cells(r, 2).Value = nms(r).Name wks.Cells(r, 3).Value = nms(r).RefersToRange.Address Next
Use the Add method to create a name and add it to the collection. The following example creates a new name that refers to cells A1:C20 on the worksheet named Sheet1.
Names.Add Name:="test", RefersTo:="=sheet1!$a$1:$c$20"
Use Names (index), where index is the name index number or defined name, to return a single Name object. The following example deletes the name mySortRange from the active workbook.
ActiveWorkbook.Names("mySortRange").Delete
This example uses a named range as the formula for data validation. This example requires the validation data to be on Sheet 2 in the range A2:A100. This validation data is used to validate data entered on Sheet1 in the range D2:D10.
Sub Add_Data_Validation_From_Other_Worksheet() 'The current Excel workbook and worksheet, a range to define the data to be validated, and the target range 'to place the data in. Dim wbBook As Workbook Dim wsTarget As Worksheet Dim wsSource As Worksheet Dim rnTarget As Range Dim rnSource As Range 'Initialize the Excel objects and delete any artifacts from the last time the macro was run. Set wbBook = ThisWorkbook With wbBook Set wsSource = .Worksheets("Sheet2") Set wsTarget = .Worksheets("Sheet1") On Error Resume Next .Names("Source").Delete On Error GoTo 0 End With 'On the source worksheet, create a range in column A of up to 98 cells long, and name it "Source". With wsSource .Range(.Range("A2"), .Range("A100").End(xlUp)).Name = "Source" End With 'On the target worksheet, create a range 8 cells long in column D. Set rnTarget = wsTarget.Range("D2:D10") 'Clear out any artifacts from previous macro runs, then set up the target range with the validation data. With rnTarget .ClearContents With .Validation .Delete .Add Type:=xlValidateList, _ AlertStyle:=xlValidAlertStop, _ Formula1:="=Source" 'Set up the Error dialog with the appropriate title and message .ErrorTitle = "Value Error" .ErrorMessage = "You can only choose from the list." End With End With End Sub
Methods
- Add
- Item
Properties
- Application
- Count
- Creator
- Parent
See also
- Excel Object Model Reference
[!includeSupport and feedback]
In Excel, a workbook is one of the most important of all the Excel Objects, and it is also essential to understand how to use and refer to workbooks while writing VBA codes.
In this tutorial, we will explore all the things that you need to know. But, the first thing you need to understand are objects that are involved in using workbooks in VBA.
Objects you need to know:
- Workbooks Object
- Workbook Object
Both of these objects sound the same, but there’s a core difference between both of them.
Workbooks Object
In VBA, the workbooks object represents the collection of the workbooks that are open in Microsoft Excel. Imagine you have ten workbooks open at the same time. And you want to refer to the one workbook out of them. In that case, you need to use the workbook object to refer to that one workbook using its name.
Workbook Object
In VBA, the workbook object represents one single workbook from the entire collection of workbooks open at present in Microsoft Excel. The best way to understand this is to think about declaring a variable as a workbook that you want to use to refer to a particular workbook in the code.
Useful Links: Add Developer Tab | Visual Basic Editor | Run a Macro | Personal Macro Workbook
To work with workbooks in VBA, the first thing that you need to know is how to refer to a workbook in a macro. Here’s the happy thing: there are multiple ways to refer to a workbook. And ahead, we will explore each one of them.
1. By Name
The easiest way to refer to a workbook is to use its name. Let’s say you want to activate the workbook Book1.xlsx, in that case, the code that you need to use should be like the following:
Referring to a workbook with its name is quite simple, you need to specify the name, and that’s it. But here’s one thing that you need to take care of: if a workbook is not saved, then you need to use only the name. And if saved, then you need to use the name along with the extension.
2. By Number
When you open a workbook, Excel gives an index number to that workbook, and you can use that number to refer to a workbook. The workbook that you have opened at first will have the index number “1” and the second will have “2” and so on.
This method might seem less real to you as it’s hard to know which workbook is on which index number. But there’s one situation where this method is quite useful to use, and that’s looping through all the open workbooks.
3. By ThisWorkbook
This workbook is a property that helps you to refer to the workbook where you are writing the code. Let’s say you are writing the code in “Book1” and use the ThisWorkbook to save the workbook. Now even when you change the name of the workbook, you won’t need to change the code.
The above code counts the number of sheets in the workbook where this code is written and shows a message box with the result.
4. By ActiveWorkbook
If you want to refer to a workbook that is active, then you need to use the “ActiveWorkbook” property. The best use of this property is when you are sure which workbook is activated now. Or you have already activated the workbook that you want to work.
The above code activates the workbook “Book1” first and then uses the active workbook property to save and close the active workbook.
Access all the Methods and Properties
In VBA, whenever you refer to an object, VBA allows you to access the properties and methods that come with that object. In the same way, the workbook object comes with properties and methods. To access them, you need to define the workbook first and then enter a dot.
The moment you type a dot (.), it shows the list of properties and methods. Now, you must have a question in your mind about how to identify which one is a property and which one is a method.
Here’s the trick. If you look closely, you can identify a moving green brick and grey hand before each name on the list. So, all the properties have that grey hand before the name and methods have a moving green brick.
For example to use a Method with Workbook
Imagine you want to close a workbook (which is a method), you need to type or select “Close” from the list.
After that, you need to enter starting parentheses to get the IntelliSense to know the arguments you need to define.
With the close method, there are three arguments that you need to define, and as you can see, all these arguments are optional, and you can skip them if you want. But some methods don’t have arguments (for example: activate)
For example to use a Property with Workbook
Imagine you want to count the sheets from the workbook “book1” in that case, you need to use the “Sheets” property and then the further count property of it.
In the above code, as I said, you have book1 defined, and then the sheet property refers to all the sheets, and then the count property to count them. And when you run this code, it shows you a message box with the result.
Using “WITH” Statement with Workbook
In VBA, there’s a “With” statement that can help you work with a workbook while writing a macro efficiently. Let’s see the below example where you have three different code lines with the same workbook, i.e., ActiveWorkbook.
With the “WITH statement”, you can refer to the active workbook a single time, and use all the properties and methods that you have in the code.
- First of all, you need to start with the starting statement “With ActiveWorkbook” and end the statement with “End With”.
- After that, you need to write the code between this statement that you have in the above example.
As you can see in the above code we have referred to the ActiveWorkbook one using the WITH statement, and then all the properties and methods need to be used.
Sub vba_activeworkbook_with_statement()
With ActiveWorkbook
.Sheets.Add Count:=5
.Charts.Visible = False
.SaveAs ("C:UsersDellDesktopmyFolderbook2.xlsx")
End With
End Sub
Let me tell you a simple real-life example to make you understand everything. Imagine you ask me to go to room 215 to get the water bottle, and when I come back, you again send me to room 215 to get a pen, and then again send me back to get a laptop. Now here’s the thing: All the things that you told me to get are in room 215. So better if you sent me to room 215 and told me to get all three things at once.
Read: With – End With
Declaring a Variable as a Workbook
Sometimes you need to declare a variable as a workbook to use it further in the code. Well, this doesn’t require anything special for you to do.
- Use the DIM Statement (Declare).
- Write the name of the Variable.
- Define the type of the variable as Workbook.
Dealing with Errors
When you work with a workbook(s) object in VBA, there are chances that you need to deal with errors as well. Take an example of the “Run-time Error 9: Subscript out of Range” error. This error can occur for various reasons.
- The workbook that you are trying to refer to is not opened.
- Might be you have misspelled the name.
- The workbook you are referring to is not yet saved and you are using the extension along with the name.
- If you are using the index number to refer to a workbook and the number you have used is greater than the total number of workbooks open.