Our daily Excel activities can be automated using VBA. Here we have created an example of creating the Name range in Excel using VBA.
Lets’ say we have below given data for which we have create the Names–
We have created a button on the Home tab and assigned the macro on this button.
Select the entire data and click on this button. All the names will be created. The first row will be considered headers.
Below is the VBA code to create multiple Names with VBA –
Option Explicit Sub Create_Name() Dim rng As Range Set rng = Selection Dim i As Integer Dim n As Long Dim new_range As Range Dim col_num As Integer Dim first_Row As Long Dim last_row As Long For i = 1 To rng.Columns.Count For n = rng.Rows.Count To 1 Step -1 col_num = rng.Columns(i).Column first_Row = rng.Rows(1).Row last_row = rng.Rows(n).Row If Cells(last_row, col_num).Value <> "" Then Set new_range = Range(Cells(first_Row, col_num), Cells(last_row, col_num)) new_range.CreateNames Top:=True Exit For End If Next n Next i MsgBox "Done" End Sub
Click here to download the Practice file-