Vba excel создать имя

Содержание

  1. Names.Add method (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Example
  6. Support and feedback
  7. Объект Name (Excel)
  8. Замечания
  9. Объекты application, Workbook и Worksheet
  10. Объекты range
  11. Пример
  12. Методы
  13. Свойства
  14. См. также
  15. Поддержка и обратная связь
  16. Объект Names (Excel)
  17. Замечания
  18. Пример
  19. Методы
  20. Свойства
  21. См. также
  22. Поддержка и обратная связь
  23. Names object (Excel)
  24. Remarks
  25. Example
  26. Methods
  27. Properties
  28. See also
  29. Support and feedback
  30. Метод Names.Add (Excel)
  31. Синтаксис
  32. Параметры
  33. Возвращаемое значение
  34. Пример
  35. Поддержка и обратная связь

Names.Add method (Excel)

Defines a new name for a range of cells.

Syntax

expression.Add (Name, RefersTo, Visible, MacroType, ShortcutKey, Category, NameLocal, RefersToLocal, CategoryLocal, RefersToR1C1, RefersToR1C1Local)

expression A variable that represents a Names object.

Parameters

Name Required/Optional Data type Description
Name Optional Variant Specifies the text, in English, to use as the name if the NameLocal parameter is not specified. Names cannot include spaces and cannot be formatted as cell references.
RefersTo Optional Variant Describes what the name refers to, in English, using A1-style notation, if the RefersToLocal, RefersToR1C1, and RefersToR1C1Local parameters are not specified.

NOTE: Nothing is returned if the reference does not exist. Visible Optional Variant True specifies that the name is defined as visible. False specifies that the name is defined as hidden. A hidden name does not appear in the Define Name, Paste Name, or Goto dialog box. The default value is True. MacroType Optional Variant The macro type, determined by one of the following values:

1 — User-defined function (Function procedure)

2 — Macro (Sub procedure)

3 or omitted — None (the name does not refer to a user-defined function or macro)

ShortcutKey Optional Variant Specifies the macro shortcut key. Must be a single letter, such as «z» or «Z». Applies only for command macros. Category Optional Variant The category of the macro or function if the MacroType argument equals 1 or 2. The category is used in the Function Wizard. Existing categories can be referred to either by number, starting at 1, or by name, in English. Excel creates a new category if the specified category does not exist. NameLocal Optional Variant Specifies the localized text to use as the name if the Name parameter is not specified. Names cannot include spaces and cannot be formatted as cell references. RefersToLocal Optional Variant Describes what the name refers to, in localized text using A1-style notation, if the RefersTo, RefersToR1C1, and RefersToR1C1Local parameters are not specified. CategoryLocal Optional Variant Specifies the localized text that identifies the category of a custom function if the Category parameter is not specified. RefersToR1C1 Optional Variant Describes what the name refers to, in English using R1C1-style notation, if the RefersTo, RefersToLocal, and RefersToR1C1Local parameters are not specified. RefersToR1C1Local Optional Variant Describes what the name refers to, in localized text using R1C1-style notation, if the RefersTo, RefersToLocal, and RefersToR1C1 parameters are not specified.

Return value

A Name object that represents the new name.

Example

This example defines a new name for the range A1:D3 on Sheet1 in the active workbook.

Nothing is returned if Sheet1 does not exist.

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 (Excel)

Представляет определенное имя для диапазона ячеек. Имена могут быть встроенными именами, например базами данных, Print_Area и Auto_Open, или пользовательскими именами.

Замечания

Объекты application, Workbook и Worksheet

Объект Name является членом коллекции Names для объектов Application, Workbook и Worksheet . Используйте name (index), где index — это номер индекса имени или определенное имя, чтобы вернуть один объект Name .

Номер индекса указывает положение имени в коллекции. Имена размещаются в алфавитном порядке, от a до z, и регистр не учитывается.

Объекты range

Хотя объект Range может иметь несколько имен, коллекция Имен для объекта Range отсутствует. Используйте имя с объектом Range , чтобы вернуть имя из списка имен (отсортированных в алфавитном порядке), назначенных диапазону.

Пример

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

В следующем примере имя mySortRange удаляется из активной книги.

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

В следующем примере задается свойство Visible для имени, присвоенного ячейкам A1:B1 на первом листе.

Методы

Свойства

См. также

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

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

Источник

Объект 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.

Источник

Метод Names.Add (Excel)

Определяет новое имя для диапазона ячеек.

Синтаксис

expression. Add (Name, RefersTo, Visible, MacroType, ShortcutKey, Category, NameLocal, RefersToLocal, CategoryLocal, RefersToR1C1, RefersToR1C1Local)

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

Параметры

Имя Обязательный или необязательный Тип данных Описание
Name Необязательно заполнять. Variant Указывает текст на английском языке, который будет использоваться в качестве имени, если параметр NameLocal не указан. Имена не могут содержать пробелы и не могут быть отформатированы в виде ссылок на ячейки.
RefersTo Необязательный Variant Описывает, на что ссылается имя на английском языке с помощью нотации в стиле A1, если параметры RefersToLocal, RefersToR1C1 и RefersToR1C1Local не указаны.

ПРИМЕЧАНИЕ. Если ссылка не существует, ничего не возвращается. Visible Необязательный Variant Значение True указывает, что имя определяется как видимое. Значение False указывает, что имя определено как скрытое. Скрытое имя не отображается в диалоговом окне Определение имени, Имя вставки или Goto . Значение по умолчанию — True. MacroType Необязательный Variant Тип макроса, определяемый одним из следующих значений:

1 — определяемая пользователем функция (процедура функции )

2 . Макрос (вложенная процедура)

3 или опущено — нет (имя не ссылается на определяемую пользователем функцию или макрос)

ShortcutKey Необязательный Variant Указывает сочетание клавиш макросов. Должна быть одна буква, например «z» или «Z». Применяется только для макросов команд. Категория Необязательный Variant Категория макроса или функции, если аргумент MacroType равен 1 или 2. Категория используется в мастере функций. На существующие категории можно ссылаться либо по номеру, начиная с 1, либо по имени на английском языке. Excel создает новую категорию, если указанная категория не существует. NameLocal Необязательный Variant Указывает локализованный текст, который будет использоваться в качестве имени, если параметр Name не указан. Имена не могут содержать пробелы и не могут быть отформатированы в виде ссылок на ячейки. RefersToLocal Необязательный Variant Описывает, на что ссылается имя, в локализованном тексте с использованием нотации в стиле A1, если параметры RefersTo, RefersToR1C1 и RefersToR1C1Local не указаны. CategoryLocal Необязательный Variant Указывает локализованный текст, определяющий категорию пользовательской функции, если параметр Category не указан. RefersToR1C1 Необязательный Variant Описывает, на что ссылается имя, на английском языке с использованием нотации в стиле R1C1, если не указаны параметры RefersTo, RefersToLocal и RefersToR1C1Local . RefersToR1C1Local Необязательный Variant Описывает, на что ссылается имя, в локализованном тексте с использованием нотации в стиле R1C1, если параметры RefersTo, RefersToLocal и RefersToR1C1 не указаны.

Возвращаемое значение

Объект Name , представляющий новое имя.

Пример

В этом примере определяется новое имя диапазона A1:D3 на Листе1 в активной книге.

Если Sheet1 не существует, ничего не возвращается.

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

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

Источник

Skip to content

Names in Excel VBA – Explained with Examples!

  • Adding Names in Excel VBA

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:

Adding Names in Excel VBA

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Double click on ThisWorkbook from Project Explorer
  4. Copy the above code and Paste in the code window
  5. Press F5
  6. GoTo Sheet1 and Select Range A1 to D10
  7. 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:

Deleting Names in Excel VBA

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Double click on ThisWorkbook from Project Explorer
  4. Copy the above code and Paste in the code window
  5. Press F5
  6. GoTo Sheet1 and Select Range A1 to D10
  7. 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:

Hide UnHide Names in Excel VBA

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Double click on ThisWorkbook from Project Explorer
  4. Copy the above code and Paste in the code window
  5. Press F5
  6. GoTo Sheet1 and Select Range A1 to D10
  7. You should see the following example
Example File

Download the example file and Explore it.
Analysistabs – Hide UnHide Names in excel Workboobk

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

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
Excel VBA Project Management Templates
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

  1. Eric W
    April 30, 2015 at 11:17 AM — Reply

    I 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

  2. Amar
    September 9, 2015 at 5:23 PM — Reply

    Can this defined name be used for coding or in vba editor

  3. PNRao
    September 11, 2015 at 11:51 PM — Reply

    Hi 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!

  4. Silke Flink
    September 12, 2015 at 12:35 AM — Reply

    Thank 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

  5. PNRao
    September 13, 2015 at 1:48 AM — Reply

    Hi,
    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

With Our Professional and Premium Project Management Templates!

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.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

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]

Содержание

  • 1 Add the name to the Names collection associated with the worksheet, which only includes the names that are local to that worksheet
  • 2 create a global name that refers to a range using the Add method of the Workbook object»s Names collection
  • 3 Create a local name
  • 4 Create a name based on a Range
  • 5 Define a name by referring a workbook
  • 6 Define a name by referring the selection cell address
  • 7 renames an existing name:

Add the name to the Names collection associated with the worksheet, which only includes the names that are local to that worksheet

   <source lang="vb">

Sub nameRef()

    Worksheets("Sheet1").Names.add name:="Costs", RefersTo:="=Sheet1!$F$10:$F$12"

End Sub
«Using the Name Property of the Range Object
Sub name()

    range("A1:D10").name = "SalesData"

End Sub

</source>
   
  

create a global name that refers to a range using the Add method of the Workbook object»s Names collection

   <source lang="vb">

Sub add()

    Names.add name:="Data", RefersTo:="=Sheet1!$D$10:$D$12"

End Sub

</source>
   
  

Create a local name

   <source lang="vb">

Sub localDemo()

    Names.add name:="Sheet1!Sales", RefersTo:="=Sheet1!$E$10:$E$12"

End Sub

</source>
   
  

Create a name based on a Range

   <source lang="vb">

Sub nameName()

   range("A1:F6").name = "Fruits"

End Sub

</source>
   
  

Define a name by referring a workbook

   <source lang="vb">

Sub DefineName3()

 ActiveWorkbook.names.Add Name:="WorkArea", RefersTo:="=" + ActiveWorkbook.Sheets("sheet1").[A1].CurrentRegion.Address(External:=True)
 Debug.Print Range("WorkArea").Address(External:=True)

End Sub

</source>
   
  

Define a name by referring the selection cell address

   <source lang="vb">

Sub DefineName2()

 ActiveWorkbook.Activate
 [A1].CurrentRegion.Activate
 ActiveWorkbook.Names.Add Name:="WorkArea", RefersTo:="=" + Selection.Address
 Debug.Print Range("WorkArea").Address(External:=True)

End Sub

</source>
   
  

renames an existing name:

   <source lang="vb">

Sub nameName2()

   Names("Fruits").name = "Produce"

End Sub

</source>
  • Что такое имя VBA?

Что такое имя VBA?

VBA NAME — это оператор, который можно использовать для перемещения файлов между дисками, и при перемещении файлов мы можем также переименовать перемещаемый файл.

  • Что если вы хотите скопировать файл, но вставить с другим именем ???
  • Что вы хотите скопировать файл, но удалить файл в исходной папке исходных файлов?
  • С ручной работой мы делаем все это без особых проблем, но если ваш VBA-проект требует, чтобы все это было сделано в середине выполнения кода, как вы это сделаете?

В этой статье мы покажем вам, как сделать все это, используя «Заявление об имени» в VBA. Читай дальше…

Что делает оператор Name в VBA?

Когда вы слышите слово «имя», что приходит на ум? Первое, что я получил, было «Имя листа» и «Имя книги».

Переименование может быть сделано в том же каталоге или папке, а не на разных дисках. Давайте посмотрим на синтаксис оператора NAME.

 Имя OldName как NewName 
  • Старое имя: это не что иное, как текущее имя файла в указанном пути к папке.
  • Новое имя: при перемещении файла каким должно быть новое имя, которое будет ему присвоено?

Мы должны помнить одну вещь: оператор NAME используется для перемещения и переименования файлов, а не для создания какого-либо файла, папки или каталога.

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

Как использовать имя VBA в Excel?

Мы узнаем, как использовать функцию имени VBA с несколькими примерами в Excel.

Вы можете скачать этот шаблон Excel с именем VBA здесь — Шаблон Excel с именем VBA

Пример № 1 — Имя VBA

Посмотрите на простой пример изменения имени файла в той же папке. Например, у меня есть файл в папке ниже.

С помощью этого файла я хочу переименовать файл «Продажи в апреле 2019.xlsx» в «Апрель 2019.xlsx». Это можно сделать с помощью оператора NAME. Выполните следующие шаги, чтобы применить код.

Шаг 1: Добавьте новый модуль.

Шаг 2: Запустите подпроцедуру.

Код:

 Sub FileCopy_Example1 () End Sub 

Шаг 3: Объявите две переменные в виде строки.

Код:

 Sub FileCopy_Example1 () Dim OldName As String Dim NewName As String End Sub 

Шаг 4: Для Old, Name Variable назначьте путь к папке и имя файла с расширением.

Код:

 Sub FileCopy_Example1 () Dim OldName As String Dim NewName As String OldName = "D:  VPB File  April Files  New Excel  SalesApril.xlsx" End Sub 

Шаг 5: Для переменной New Name мы упомянем тот же путь, но изменим только имя файла.

Код:

 Sub FileCopy_Example1 () Dim OldName As String Dim NewName As String OldName = "D:  VPB File  April Files  New Excel  SalesApril.xlsx" NewName = "D:  VPB File  April Files  New Excel  April.xlsx" End Sub 

Шаг 6: Теперь я буду использовать оператор NAME.

Код:

 Sub FileCopy_Example () Dim OldName As String Dim NewName As String OldName = "D:  VPB File  April Files  New Excel  SalesApril.xlsx" NewName = "D:  VPB File  April Files  New Excel  April.xlsx" Имя OldName Как NewName End Sub 

Шаг 7: Старое имя и новое имя — это переменные, которые содержат ссылки на пути. Теперь выполните код, чтобы увидеть магию.

В этой же папке он изменил имя файла с «Продажи апреля 2019.xlsx» на «Апреля 2019.xlsx».

Это способ изменения имени файла в той же папке, как и при переходе из одной папки в другую.

Пример №2 — переход из одной папки в другую

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

 Sub FileCopy_Example1 () Dim OldName As String Dim NewName As String OldName = "D:  VPB File  April Files  New Excel  April 1.xlsx" NewName = "D:  VPB File  April Files  Конечное расположение  April.xlsx "Имя OldName как NewName End Sub 

Если вы заметите разницу между нашим предыдущим кодом и этим кодом, мы изменили Новое имя на другую папку на том же диске.

Теперь я выполню этот код и увижу влияние в обеих папках.

Новая папка:

В новой папке мы получили новый лист с именем «Апрель 2019.xlsx». Теперь посмотрите на старую папку.

Старая папка:

Там написано «Эта папка пуста».

Это не похоже на наш метод копирования файлов. Оператор Name удалил исходный файл из старой папки и переместил в новую папку с новым именем, как мы указали.

Таким образом, мы можем перемещать файлы из одной папки в другую с разными именами, используя оператор «NAME».

Рекомендуемые статьи

Это руководство к VBA Name. Здесь мы обсуждаем, как использовать функцию имени VBA Excel вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Функция копирования и вставки в VBA
  2. Функция подстроки Excel
  3. Индекс VBA вне диапазона
  4. FileCopy в VBA (примеры)

Excel VBA Name

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.

Changing the Name

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.

VBA Name Module

Step 2: Start the subprocedure.

Code:

Sub FileCopy_Example1()

End Sub

VBA Name - subprocedure

Step 3: Declare two variables as a string.

Code:

Sub FileCopy_Example1()

Dim OldName As String
Dim NewName As String

End Sub

VBA Name - String

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

File Location

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

New Name variable

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

Using the Name Statement

Step 7: Old Name & New Name are the variables which hold path references. Now execute the code to see the magic.

New File

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

Copy Paste

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:

VBA Final Location

In the new folder, we got the new sheet named as “April 2019.xlsx”. Now, look at the Old Folder.

Old Folder:

Old file

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 –

  1. VBA Copy Paste
  2. VBA RGB
  3. VBA Subscript out of Range
  4. FileCopy in VBA

Понравилась статья? Поделить с друзьями:
  • Vba excel создать директорию
  • Vba excel создать диаграмму
  • Vba excel создание файла word
  • Vba excel создание ссылки
  • Vba excel создание списков