0

I have the following code which I am trying to get to name the entire A and B columns range according to the worksheet tab name. I want each A:B range of cells in each worksheet to be named RoomCode_ + the name of the excel sheet tab.

So for example if I had 3 sheets called XYZ, ABC and DEF, then my cell range names for those 3 sheets respectively should be:

RoomCode_XYZ
RoomCode_ABC
RoomCode_DEF

I would typically do this manually by highlighting the cell range and just typing the range name I wanted, however I have over 150 tabs and would like to be able to do them all automatically through this process.

Sub nameRanges()

Set wbook = ActiveWorkbook

For Each sht In wbook.Worksheets
    sht.Activate

RangeName = "RoomCode_" + ActiveSheet.Name
  CellName = "A:B"

  Set cell = ActiveWorksheets.Range(CellName)
  ActiveWorksheets.Names.Add Name:=RangeName, RefersTo:=cell

  Next sht

End Sub
Bob
  • 27
  • 7
  • I believe naming rules for worksheets and ranges are different, and that you'll run into problems if a sheet/tab has spaces in its name, for example. – Mathieu Guindon Jun 29 '16 at 16:30

3 Answers3

1

Just a bit of refactoring to get what you need. Biggest this to work directly with objects and eliminate the Active... stuff.

Also ActiveWorksheets is not proper syntax in any way.

Sub nameRanges()

    Dim wbook As Workbook
    Set wbook = ThisWorkbook

    Dim sht As Worksheet

    For Each sht In wbook.Worksheets

        Dim RangeName As String, CellName As String

        RangeName = "RoomCode_" + sht.Name
        CellName = "A:B"

        Dim cell As Range

        Set cell = sht.Range(CellName)

        sht.Names.Add Name:=RangeName, RefersTo:=cell


    Next sht

End Sub
Community
  • 1
  • 1
Scott Holtzman
  • 27,099
  • 5
  • 37
  • 72
0

Here's another way:

Option Explicit

Sub nameRanges()

Dim sht As Worksheet
Dim RangeName As String
Dim cell As String

For Each sht In ActiveWorkbook.Worksheets
    RangeName = "RoomCode_" + sht.Name
    cell = "=" & sht.Name & "!" & "A:B"
    Names.Add Name:=RangeName, RefersTo:=cell
Next sht

End Sub
Brian
  • 2,078
  • 1
  • 15
  • 28
0

I think that you would want to add the names to the workbook names collection. The way it is now you'll still have to reference the individual worksheet before you can access the name.

WorkSheets("RoomCode").Range("RoomCode_XYZ")

By adding the names to the workbook you'll be able to access no matter the ActiveSheet.

Range("RoomCode_XYZ")

Sub nameRanges()

    Dim wbook As Workbook
    Set wbook = ThisWorkbook

    Dim sht As Worksheet

    For Each sht In wbook.Worksheets

        Dim RangeName As String, CellName As String

        RangeName = "RoomCode_" + sht.Name
        CellName = "A:B"

        Dim cell As Range

        Set cell = sht.Range(CellName)

        ThisWorkBook.Names.Add Name:=RangeName, RefersTo:=cell


    Next sht

End Sub