Names in Excel VBA – Explained with Examples!
Names in Excel VBA makes our job more easier. We can save lot of time using Names. It is easy to maintain the formulas, Cells,Ranges and Tables. You can define the names once in the workbook and use it across the workbook. The following examples will show some of the Names daily operations.
- Adding Names in Excel VBA
- Deleting Names in Excel VBA
- Hide UnHide Names in Excel VBA
Adding Names in Excel VBA:
Sometimes you may need to Add name to a particular range in excel worksheet. We can manage range names in excel vba with using names collection.
- Solution
- Code
- Output
- Example File
Adding Names in Excel VBA – Solution(s):
We can use Names.Add method or Name property of a range for adding names in excel VBA.
We can create range name in the following way. It contains several properties.We must define Name and the Refers To property.please find the following example.The following code creates a name “MyData” and referring to sheet1 of a range(“$A$1:$E$10”)
Code:
'Naming a range Sub sbNameRange() 'Adding a Name Names.Add Name:="myData", RefersTo:="=Sheet1!$A$1:$E$10" 'OR 'You can use Name property of a Range Sheet1.Range("$A$1:$E$10").Name = "myData" End Sub
Output:
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Double click on ThisWorkbook from Project Explorer
- Copy the above code and Paste in the code window
- Press F5
- GoTo Sheet1 and Select Range A1 to D10
- You should see the following example
Example File
Download the example file and Explore it.
Analysistabs – Adding Name to Range in excel Workboobk
Deleting Names in Excel VBA:
Sometimes you may need to Delete range name in existing excel workbook for cleaning broken references in excel workbook.
- Solution
- Code
- Output
- Example File
Deleting Names in Excel VBA – Solution(s):
You can use Delete method for deleting existing names in excel workbook.We can delete range name in the following way.please find the following example.The following code Deletes a name “MyData”.
Code:
'Deleting Names Sub sbDeleteName() 'myData=Sheet1.range("A1:E10") Names("myData").Delete End Sub
Output:
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Double click on ThisWorkbook from Project Explorer
- Copy the above code and Paste in the code window
- Press F5
- GoTo Sheet1 and Select Range A1 to D10
- You should see the following example
Example File
Download the example file and Explore it.
Analysistabs – Deleting Name to Range in excel Workboobk
Hide UnHide Names in Excel VBA:
Sometimes you may need to Hide UnHide names in Excel VBA.
- Solution
- Code
- Output
- Example File
Hide UnHide names in Excel VBA – Solution(s):
You Can Hide UnHide Names in Excel VBA using Visible Property in the following way. when we set visible proprty to false, We dont see defined range name . when we set visible proprty to true, We can see defined range name .
Code:
'Hiding a Name Sub sbHideName() Names("myData").Visible = False End Sub 'UnHide aName Sub sbUnHideName() Names("myData").Visible = True End Sub
Output:
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Double click on ThisWorkbook from Project Explorer
- Copy the above code and Paste in the code window
- Press F5
- GoTo Sheet1 and Select Range A1 to D10
- You should see the following example
Example File
Download the example file and Explore it.
Analysistabs – Hide UnHide Names in excel Workboobk
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Related Posts
-
- Adding Names in Excel VBA:
- Adding Names in Excel VBA – Solution(s):
- Deleting Names in Excel VBA:
- Deleting Names in Excel VBA – Solution(s):
- Hide UnHide Names in Excel VBA:
- Hide UnHide names in Excel VBA – Solution(s):
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
5 Comments
-
Eric W
April 30, 2015 at 11:17 AM — ReplyI am having a problem copying Ranges from one point to another in Excel using VBA.
I have tried several methods and get the same result any way I’ve tried
When the copy action is triggered, the destination has the copy from the header row in the destination
Example: Range(“U14:AO14”).Copy Destination:=Range(“A40”)
I am receiving the data from U2:AO2.
I have named the range by selection using the spreadsheet name window. The array that shows in the window shows the correct value. The destination is correct.Do you have a clue what is happening, or what I am doing wrong?
Thank You -
Amar
September 9, 2015 at 5:23 PM — ReplyCan this defined name be used for coding or in vba editor
-
PNRao
September 11, 2015 at 11:51 PM — ReplyHi Amar,
Yes! we can use the defined names in VBA. Example:Sheet1.Range("$A$1:$E$10").Name = "myData" Range("myData").Interior.ColorIndex = 3
here, myData is a user defined name and the above code will change the background color of the defined range.
Thanks-PNRao! -
Silke Flink
September 12, 2015 at 12:35 AM — ReplyThank you for this post. I was wondering if it is possible to address a dynamic name range in VBA. I have a named range (though I use a lookup-function in the name manager) that is visible in the name manager and can be used in formulas in the Excel sheet.
I tried this
dim Taxes_from_Sales as Range
Set Taxes_from_Sales = Range(“Taxes_from_Sales”)whereas “Taxes_from_Sales” is a excel Lookup defined name range. VBA doesn’t recognize it cause of the formula.
Any idea how to approach this without writing Lookup in VBA?
Thanks for help
silke
-
PNRao
September 13, 2015 at 1:48 AM — ReplyHi,
It works for dynamic range. In your case, Lookup functions always returns a value, and we need a range to use in VBA.I have tried the below example and its working fine:
Sub DynamicNamedRange() 'Adding a dynamic Name Names.Add Name:="test", RefersTo:="=OFFSET(Sheet1!$A$1,0,0,COUNTA(Sheet1!A:A),1)" 'Entering sample data For i = 1 To 10 Cells(i, 1) = i Next 'Formatting dynamic range Range("test").Interior.ColorIndex = 3 End Sub
Thanks-PNRao!
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
Вступление
Тема должна включать информацию, конкретно связанную с именованными диапазонами в Excel, включая методы создания, изменения, удаления и доступа к определенным именованным диапазонам.
Определить именованный диапазон
Использование именованных диапазонов позволяет описать значение содержимого ячейки (я) и использовать это определенное имя вместо фактического адреса ячейки.
Например, формулу =A5*B5
можно заменить на =Width*Height
чтобы упростить чтение и понимание формулы.
Чтобы определить новый именованный диапазон, выберите ячейку или ячейки для имени, а затем введите новое имя в поле «Имя» рядом с панелью формул.
Примечание. Именованные диапазоны по умолчанию относятся к глобальной области, что означает, что к ним можно получить доступ из любой точки книги. Старые версии Excel позволяют дублировать имена, поэтому необходимо избегать дублирования имен глобальной области, иначе результаты будут непредсказуемыми. Используйте вкладку «Диспетчер имен» на вкладке «Формулы», чтобы изменить область действия.
Создайте новый именованный диапазон под названием «MyRange», назначенный ячейке A1
ThisWorkbook.Names.Add Name:="MyRange", _
RefersTo:=Worksheets("Sheet1").Range("A1")
Удалить определенный именованный диапазон по имени
ThisWorkbook.Names("MyRange").Delete
Доступ к именованному диапазону по имени
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("MyRange")
Call MsgBox("Width = " & rng.Value)
Доступ к названию диапазона с ярлыком
Как и любой другой диапазон , именованные диапазоны могут быть доступны напрямую с помощью ярлыка, который не требует создания объекта Range
. Три строки из выдержки из вышеприведенного кода могут быть заменены одной строкой:
Call MsgBox("Width = " & [MyRange])
Примечание. Свойством по умолчанию для диапазона является его значение, поэтому
[MyRange]
совпадает с[MyRange].Value
Вы также можете вызвать методы в диапазоне. Следующий выбирает MyRange
:
[MyRange].Select
Примечание. Одно предостережение состоит в том, что нотация ярлыка не работает со словами, которые используются в другом месте библиотеки VBA. Например, диапазон с именем
Width
не будет доступен как[Width]
но будет работать, как ожидалось, при доступе черезThisWorkbook.Worksheets("Sheet1").Range("Width")
Управление именованным диапазоном (диапазонами) с помощью диспетчера имен
Вкладка «Формулы»> «Определенная группа имен»> «Диспетчер имен»
Именованный менеджер позволяет:
- Создайте или измените имя
- Создать или изменить ссылку на ячейку
- Создать или изменить область действия
- Удалить существующий именованный диапазон
Named Manager предоставляет полезный быстрый поиск неработающих ссылок.
Именованные массивы диапазонов
Примерный лист
Код
Sub Example()
Dim wks As Worksheet
Set wks = ThisWorkbook.Worksheets("Sheet1")
Dim units As Range
Set units = ThisWorkbook.Names("Units").RefersToRange
Worksheets("Sheet1").Range("Year_Max").Value = WorksheetFunction.Max(units)
Worksheets("Sheet1").Range("Year_Min").Value = WorksheetFunction.Min(units)
End Sub
Результат
November 15, 2015/
Chris Newman
What Is A Named Range?
Creating a named range allows you to refer to a cell or group of cells with a custom name instead of the usual column/row reference. The HUGE benefit to using Named Ranges is it adds the ability to describe the data inside your cells. Let’s look at a quick example:
Can you tell if shipping costs are charged with the product price?
-
= (B7 + B5 * C4) * (1 + A3)
-
=(ShippingCharge + ProductPrice * Quantity) * (1 + TaxRate)
Hopefully, you can clearly see option number TWO gives you immediate insight to whether the cost of the products includes shipping costs. This allows the user to easily understand how the formula is calculating without having to waste time searching through cells to figure out what is what.
How Do I Use Named Ranges?
As a financial analyst, I play around with a bunch of rates. Examples could be anything from a tax rate to an estimated inflation rate. I use named ranges to organize my variables that either are changed infrequently (ie Month or Year) or something that will be static for a good amount of time (ie inflation rate). Here are a list of common names I use on a regular basis:
-
ReportDate
-
Year
-
Month
-
FcstID
-
TaxRate
-
RawData
Creating Unique Names On The Fly
It is super easy to create a Named Range. All you have to do is highlight the cell(s) you want to reference and give it a name in the Name Box. You name cannot have any spaces in it, so if you need to separate words you can either capitalize the beginning of each new word or use an underscore (_). Make sure you hit the ENTER key after you have finished typing the name to confirm the creation of the Named Range.
As a side note, any Named Range created with the Name Box has a Workbook scope. This means the named range can be accessed by any worksheet in your Excel file.
Creating Names With The «Name Manager»
If you want to customize your named ranges even more, you can open up the Name Manager (Formulas tab > Defined Names group > Name Manager button) to edit and create new named ranges.
I won’t go into great detail in this article, but know that with the Name Manager you can
-
Change the name of an existing Named Range
-
Change the reference formula
-
Specify the scope (what worksheets the name can be accessed from)
On To The VBA
Now that you have had a brief overview on Named Ranges, lets dig into some VBA macros you can use to help automate the use of Named Ranges.
Add A Named Range
The below VBA code shows ways you can create various types of named ranges.
Sub NameRange_Add()
‘PURPOSE: Various ways to create a Named Range
‘SOURCE: www.TheSpreadsheetGuru.com
Dim cell As Range
Dim rng As Range
Dim RangeName As String
Dim CellName As String
‘Single Cell Reference (Workbook Scope)
RangeName = «Price»
CellName = «D7»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
‘Single Cell Reference (Worksheet Scope)
RangeName = «Year»
CellName = «A2»
Set cell = Worksheets(«Sheet1»).Range(CellName)
Worksheets(«Sheet1»).Names.Add Name:=RangeName, RefersTo:=cell
‘Range of Cells Reference (Workbook Scope)
RangeName = «myData»
CellName = «F9:J18»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
‘Secret Named Range (doesn’t show up in Name Manager)
RangeName = «Username»
CellName = «L45»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell, Visible:=False
End Sub
Loop Through Named Ranges
This VBA macro code shows how you can cycle through the named ranges within your spreadsheet.
Sub NamedRange_Loop()
‘PURPOSE: Delete all Named Ranges in the Active Workbook
‘SOURCE: www.TheSpreadsheetGuru.com
Dim nm As Name
‘Loop through each named range in workbook
For Each nm In ActiveWorkbook.Names
Debug.Print nm.Name, nm.RefersTo
Next nm
‘Loop through each named range scoped to a specific worksheet
For Each nm In Worksheets(«Sheet1»).Names
Debug.Print nm.Name, nm.RefersTo
Next nm
End Sub
Delete All Named Ranges
If you need to clean up a bunch of junk named ranges, this VBA code will let you do it.
Sub NamedRange_DeleteAll()
‘PURPOSE: Delete all Named Ranges in the ActiveWorkbook (Print Areas optional)
‘SOURCE: www.TheSpreadsheetGuru.com
Dim nm As Name
Dim DeleteCount As Long
‘Delete PrintAreas as well?
UserAnswer = MsgBox(«Do you want to skip over Print Areas?», vbYesNoCancel)
If UserAnswer = vbYes Then SkipPrintAreas = True
If UserAnswer = vbCancel Then Exit Sub
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Loop through each name and delete
For Each nm In ActiveWorkbook.Names
If SkipPrintAreas = True And Right(nm.Name, 10) = «Print_Area» Then GoTo Skip
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Delete Named Range
nm.Delete
DeleteCount = DeleteCount + 1
Skip:
‘Reset Error Handler
On Error GoTo 0
Next
‘Report Result
If DeleteCount = 1 Then
MsgBox «[1] name was removed from this workbook.»
Else
MsgBox «[» & DeleteCount & «] names were removed from this workbook.»
End If
End Sub
Delete Named Ranges with Error References
This VBA code will delete only Named Ranges with errors in them. These errors can be caused by worksheets being deleted or rows/columns being deleted.
Sub NamedRange_DeleteErrors()
‘PURPOSE: Delete all Named Ranges with #REF error in the ActiveWorkbook
‘SOURCE: www.TheSpreadsheetGuru.com
Dim nm As Name
Dim DeleteCount As Long
‘Loop through each name and delete
For Each nm In ActiveWorkbook.Names
If InStr(1, nm.RefersTo, «#REF!») > 0 Then
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Delete Named Range
nm.Delete
DeleteCount = DeleteCount + 1
End If
Skip:
‘Reset Error Handler
On Error GoTo 0
Next
‘Report Result
If DeleteCount = 1 Then
MsgBox «[1] errorant name was removed from this workbook.»
Else
MsgBox «[» & DeleteCount & «] errorant names were removed from this workbook.»
End If
End Sub
Anything Missing From This Guide?
Let me know if you have any ideas for other useful VBA macros concerning Named Ranges. Or better yet, share with me your own macros and I can add them to the article for everyone else to see! I look forward to reading your comments below.
About The Author
Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.
Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!
— Chris
Founder, TheSpreadsheetGuru.com
What is VBA Name?
VBA NAME is a statement which can be used to move files from across drives and while moving the files we can rename the moving file as well.
- What if you want to copy the file but paste with different name???
- What is you want to copy the file but to delete the file in the original source folder??
- With manual work we do all this without much trouble, but if your VBA project requires all of these to be done in the middle of the code execution how will you do??
In this article, we will show you how to do all of these using “Name Statement” in VBA. Read on…
What Does Name Statement Do in VBA?
When you hear the word “Name” what comes to your mind?? The first thing I got was “Worksheet Name” and “Workbook Name”.
Renaming can be done within the same directory or folder, not across drives. Let’s look at the syntax of the NAME statement.
Name OldName as NewName
- Old Name: This is nothing but the current name of the file in the mentioned folder path.
- New Name: While moving the file what should be the new name to be allocated to it?
One thing we need to remember is, NAME statement is used to move and rename the files not to create any file, folder or directory.
In order to move or rename the file, we need to first close the targeted file and execute the task or else we will get an error message.
How to Use VBA Name in Excel?
We will learn how to use a VBA Name Function with few examples in excel.
You can download this VBA Name Excel Template here – VBA Name Excel Template
Example #1 – VBA Name
Take a look at the simple example of changing the name of the File in the same folder. For example, I have a file in the below folder.
With this file, I want to rename the file “Sales April 2019.xlsx” to “April 2019.xlsx”. This can be done by using the NAME statement. Follow the below steps to apply the code.
Step 1: Add the new module.
Step 2: Start the subprocedure.
Code:
Sub FileCopy_Example1() End Sub
Step 3: Declare two variables as a string.
Code:
Sub FileCopy_Example1() Dim OldName As String Dim NewName As String End Sub
Step 4: For Old, Name Variable assign the folder path and file name with extension.
Code:
Sub FileCopy_Example1() Dim OldName As String Dim NewName As String OldName = " D:VPB FileApril FilesNew ExcelSalesApril.xlsx" End Sub
Step 5: For the New Name variable we will mention the same path but will change the name of the file only.
Code:
Sub FileCopy_Example1() Dim OldName As String Dim NewName As String OldName = " D:VPB FileApril FilesNew ExcelSalesApril.xlsx" NewName = " D:VPB FileApril FilesNew ExcelApril.xlsx" End Sub
Step 6: Now I will use the NAME Statement.
Code:
Sub FileCopy_Example() Dim OldName As String Dim NewName As String OldName = " D:VPB FileApril FilesNew ExcelSalesApril.xlsx" NewName = " D:VPB FileApril FilesNew ExcelApril.xlsx" Name OldName As NewName End Sub
Step 7: Old Name & New Name are the variables which hold path references. Now execute the code to see the magic.
In the same folder itself, it has changed the file name from “Sales April 2019.xlsx” to “April 2019.xlsx”.
This is the way of changing the file name in the same folder how about changing from one folder to a different folder.
Example #2 – Change from One Folder to Another
In order to move from one folder to another, we need to change the New Name path. For an example look at the below code.
Sub FileCopy_Example1() Dim OldName As String Dim NewName As String OldName = "D:VPB FileApril FilesNew ExcelApril 1.xlsx" NewName = "D:VPB FileApril FilesFinal locationApril.xlsx" Name OldName As NewName End Sub
If you observe the difference from our previous code to this code, we have changed the New Name to a different folder in the same drive.
Now I will execute this code and see the impact in both the folders.
New Folder:
In the new folder, we got the new sheet named as “April 2019.xlsx”. Now, look at the Old Folder.
Old Folder:
It says “This folder is empty”.
This is unlike our File Copy method. Name statement has removed the original file from the old folder and moved to a new folder with a new name as we specified.
Like this, we can move files from one folder to another with different names by using the “NAME” statement.
Recommended Articles
This is a guide to VBA Name. Here we discuss how to use Excel VBA Name Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Copy Paste
- VBA RGB
- VBA Subscript out of Range
- FileCopy in VBA
Содержание
- 1 Adding Comments for a name
- 2 A name can also store the data stored in an array.
- 3 Checking for the Existence of a Name
- 4 Check Name existance
- 5 Define a name by hard code the cell address
- 6 Determining which Names Overlap a Range
- 7 Enables access to named ranges in arbitrary workbooks
- 8 Fill named range with values
- 9 find out which names are overlapping the selected cells, regardless of whether they entirely contain the selected cells
- 10 Generate named range from Range object
- 11 Generate Range object from named range
- 12 Go to a name
- 13 Hide a name by setting its Visible property to False
- 14 Hide the name after it has been created:
- 15 Insert hidden name
- 16 Is Name In Workbook
- 17 Names Overlapping Selection
- 18 Range objects cannot be used with an worksheet object as superobject
- 19 Retrieving Values Stored as a Workbook Name Using the Evaluate Method
- 20 Searching for a Name
- 21 Searching for the Name of a Range
- 22 Selection Entirely In Names
- 23 Select named range
- 24 specify that the Names collection belongs to a worksheet:
- 25 Store formulas into names. The formula must start with an equals sign (=).
- 26 storing a formula in a name is the same as for a range
- 27 Storing Values in Names
- 28 use names to store numbers between sessions
- 29 use the Evaluate method equivalent to evaluate the name in VBA:
- 30 Using named ranges of cells
- 31 Using the Names Object to List All Named Ranges
<source lang="vb">
Sub addcomment()
ActiveWorkbook.Worksheets("Sheet7").Names("LocalOffice").rument = "text"
End Sub
</source>
A name can also store the data stored in an array.
<source lang="vb">
Sub NamedArray()
Dim myArray(10, 5) Dim i As Integer, j As Integer For i = 1 To 10 For j = 1 To 5 myArray(i, j) = i + j Next j Next i Names.add name:="FirstArray", RefersTo:=myArray
End Sub
</source>
Checking for the Existence of a Name
<source lang="vb">
Function NameExists(FindName As String) As Boolean
Dim Rng As Range Dim myName As String On Error Resume Next myName = ActiveWorkbook.Names(FindName).Name If Err.Number = 0 Then NameExists = True Else NameExists = False End If
End Function
</source>
Check Name existance
<source lang="vb">
Sub Main()
If NameExists("SalesData") Then MsgBox "Name Exists" Else MsgBox "Name does not exist" End If
End Sub
Function NameExists(myName As String) As Boolean
Dim X As String On Error Resume Next X = Names(myName).RefersTo If Err.Number <> 0 Then NameExists = False Err.Clear Else NameExists = True End If
End Function
</source>
Define a name by hard code the cell address
<source lang="vb">
Sub DefineName1a()
ActiveWorkbook.names.Add Name:="NameArea", RefersToR1C1:="=sheet1!R1C1:R3C1"
End Sub
</source>
Determining which Names Overlap a Range
<source lang="vb"> Sub SelectionEntirelyInNames() Dim sMessage As String Dim nmName As name Dim rngNameRange As range Dim rng As range On Error Resume Next For Each nmName In Names Set rngNameRange = Nothing Set rngNameRange = nmName.RefersToRange If Not rngNameRange Is Nothing Then If rngNameRange.Parent.name = ActiveSheet.name Then Set rng = Intersect(Selection, rngNameRange) If Not rng Is Nothing Then If Selection.Address = rng.Address Then sMessage = sMessage & nmName.name & vbCr End If End If End If End If Next nmName If sMessage = "" Then MsgBox "The selection is not entirely in any name" Else MsgBox sMessage End If End Sub </source>
Enables access to named ranges in arbitrary workbooks
<source lang="vb">
Sub ChangeValueInNamedCell2()
Dim rng As Range Set rng = Evaluate(ActiveWorkbook.names("CellXy").Name) rng.Value = "This is a named cell." Debug.Print rng.Value
End Sub
</source>
Fill named range with values
<source lang="vb">
Sub FillNameArea1()
Application.Goto Reference:=ActiveWorkbook.Names("NameArea").Name Selection.value = "Test1"
End Sub
Sub FillNameArea2()
Evaluate(ActiveWorkbook.Names("NameArea").value).value = "Test2"
End Sub
</source>
find out which names are overlapping the selected cells, regardless of whether they entirely contain the selected cells
<source lang="vb"> Sub NamesOverlappingSelection() Dim sMessage As String Dim nmName As name Dim rngNameRange As range Dim rng As range On Error Resume Next For Each nmName In Names Set rngNameRange = Nothing Set rngNameRange = range(nmName.name) If Not rngNameRange Is Nothing Then If rngNameRange.Parent.name = ActiveSheet.name Then Set rng = Intersect(Selection, rngNameRange) If Not rng Is Nothing Then sMessage = sMessage & nmName.name & vbCr End If End If End If Next nmName If sMessage = "" Then MsgBox "The selection is not entirely in any name" Else MsgBox sMessage End If End Sub </source>
Generate named range from Range object
<source lang="vb">
Sub BuildNameFromRange()
Dim rng As Range Set rng = ActiveWorkbook.Sheets("sheet1").[A1].CurrentRegion ActiveWorkbook.Names.Add Name:="NameArea", RefersTo:="=" + rng.Address(External:=True) Debug.Print Range("NameArea").Address(External:=True)
End Sub
</source>
Generate Range object from named range
<source lang="vb">
Sub BuildRangeFromName()
Dim rng As Range Set rng = Evaluate(ActiveWorkbook.names("NameArea").Value) Debug.Print rng.Address(External:=True)
End Sub
</source>
Go to a name
<source lang="vb">
Sub GotoName2()
Application.Goto Reference:= ActiveWorkbook.names("NameArea").Name, Scroll:=True
End Sub
</source>
Hide a name by setting its Visible property to False
<source lang="vb">
Sub nameRef()
Names.add name:="StoreNumber", RefersTo:=v, Visible:=False
End Sub
</source>
Hide the name after it has been created:
<source lang="vb">
Sub vis()
Names("StoreNumber").Visible = False
End Sub
</source>
Insert hidden name
<source lang="vb">
Public Sub InsertHiddenName()
Names.Add Name:="PassWord", RefersTo:="Bazonkas", Visible:=False
End Sub
</source>
Is Name In Workbook
<source lang="vb">
Option Explicit
Public Function IsNameInWorkbook(ByVal Name As String) As Boolean
Dim X As String Dim aRange As Range Application.Volatile On Error Resume Next Set aRange = Application.Caller Err.Clear If aRange Is Nothing Then X = ActiveWorkbook.Names(Name).Name Else X = aRange.Parent.Parent.Names(Name).Name End If If Err.Number = 0 Then IsNameInWorkbook = True
End Function
Public Sub TestName()
If IsNameInWorkbook(InputBox("What Name")) Then MsgBox "Name exists" Else MsgBox "Name does not exist" End If
End Sub
</source>
Names Overlapping Selection
<source lang="vb">
Public Sub NamesOverlappingSelection()
Dim Message As String Dim aName As Name Dim NameRange As Range Dim aRange As Range On Error Resume Next For Each aName In Names Set NameRange = Nothing Set NameRange = Range(aName.Name) If Not NameRange Is Nothing Then If NameRange.Parent.Name = ActiveSheet.Name Then Set aRange = Intersect(Selection, NameRange) If Not aRange Is Nothing Then Message = Message & aName.Name & vbCr End If End If End If Next aName If Message = "" Then Debug.Print "No Names are overlapping the selection" Else Debug.Print Message End If
End Sub
</source>
Range objects cannot be used with an worksheet object as superobject
<source lang="vb">
Sub ChangeValueInNamedCell1()
Range("CellXy").Value = "CellXy" Debug.Print Range("CellXy").Value
End Sub
</source>
Retrieving Values Stored as a Workbook Name Using the Evaluate Method
<source lang="vb">
Sub TestWorkbookNameValue()
Dim vValue As Variant vValue = Application.Names("SalesTaxRate").RefersTo Debug.Print "Value retrieved using RefersTo: " & vValue
End Sub
</source>
Searching for a Name
<source lang="vb"> Function IsNameInWorkbook(sName As String) As Boolean Dim s As String Dim rng As range Application.Volatile On Error Resume Next Set rng = Application.Caller Err.clear If rng Is Nothing Then s = ActiveWorkbook.Names(sName).name Else s = rng.Parent.Parent.Names(sName).name End If If Err.Number = 0 Then IsNameInWorkbook = True End Function Sub TestName() If IsNameInWorkbook(InputBox("What Name")) Then MsgBox "Name exists" Else MsgBox "Name does not exist" End If End Sub </source>
Searching for the Name of a Range
<source lang="vb"> Sub TestNameOfRange() Dim nmName As name On Error Resume Next Set nmName = Selection.name If nmName Is Nothing Then MsgBox " Selection has no name" Else MsgBox nmName.name End If End Sub </source>
Selection Entirely In Names
<source lang="vb">
Public Sub SelectionEntirelyInNames()
Dim Message As String Dim aName As Name Dim NameRange As Range Dim aRange As Range On Error Resume Next For Each aName In Names Set NameRange = Nothing Set NameRange = aName.RefersToRange If Not NameRange Is Nothing Then If NameRange.Parent.Name = ActiveSheet.Name Then Set aRange = Intersect(Selection, NameRange) If Not aRange Is Nothing Then If Selection.Address = aRange.Address Then Message = Message & aName.Name & vbCr End If End If End If End If Next aName If Message = "" Then MsgBox "The selection is not entirely in any name" Else MsgBox Message End If
End Sub
</source>
Select named range
<source lang="vb">
Sub GotoName1()
Application.Goto Reference:= _ ActiveWorkbook.names("NameArea").Name
End Sub
</source>
specify that the Names collection belongs to a worksheet:
<source lang="vb">
Sub nameAdd()
Worksheets("Sheet1").Names.add name:="F", RefersToR1C1:="=Sheet1!R1C1:R6C6"
End Sub
</source>
Store formulas into names. The formula must start with an equals sign (=).
<source lang="vb">
Sub addName()
Names.add name:="ItemsInA", RefersTo:="=COUNTA($A:$A)"
End Sub
</source>
storing a formula in a name is the same as for a range
<source lang="vb">
Sub addName()
Names.add name:="Product", RefersTo:="=OFFSET(Sheet2!$A$2,0,0,COUNTA(Sheet2!$A:$A))"
End Sub
</source>
Storing Values in Names
<source lang="vb">
Sub var()
Dim v As Variant v = 3.14159 Names.add name:="StoreNumber", RefersTo:=v v = "Sales" Names.add name:="StoreString", RefersTo:=v
End Sub
</source>
use names to store numbers between sessions
<source lang="vb">
Sub store()
NumofSales = 5123 Names.add name:="TotalSales", RefersTo:=NumofSales "Or use this: Names.add name:="TotalSales", RefersTo:=5123
End Sub
</source>
use the Evaluate method equivalent to evaluate the name in VBA:
<source lang="vb">
Sub itemA()
Names.add name:="ItemsInA", RefersTo:="=COUNTA($A:$A)" MsgBox [ItemsInA]
End Sub
</source>
Using named ranges of cells
<source lang="vb">
Option Explicit
Sub DefineName1()
Range("A3:B5").Name = "TestArea" Debug.Print Range("TestArea").Address(External:=True)
End Sub
</source>
Using the Names Object to List All Named Ranges
<source lang="vb">
Sub TestListNames()
ListWorkbookNames ThisWorkbook, ThisWorkbook.Worksheets(2).range("a2")
End Sub
Sub ListWorkbookNames(wb As Workbook, rgListStart As range)
Dim nm As name For Each nm In wb.Names rgListStart.value = nm.name rgListStart.Offset(0, 1).value = """ & nm.RefersTo Set rgListStart = rgListStart.Offset(1, 0) Next
End Sub
</source>