Excel宏根据工作表的名称命名范围选项卡名称

时间:2016-06-29 16:08:32

标签: excel vba excel-vba

我有以下代码,我试图根据工作表选项卡名称命名整个A和B列范围。我希望每个工作表中的每个A:B范围的单元格都被命名为RoomCode_ + excel工作表标签的名称。

例如,如果我有3张名为XYZ,ABC和DEF的纸张,那么这3张纸张的单元格范围名称应分别为:

RoomCode_XYZ
RoomCode_ABC
RoomCode_DEF

我通常会通过突出显示单元格范围并只键入我想要的范围名称来手动执行此操作,但是我有超过150个选项卡,并且希望能够通过此过程自动完成这些操作。

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

3 个答案:

答案 0 :(得分:1)

只需进行一些重构即可获得所需内容。最重要的是直接使用对象并消除Active...内容。

ActiveWorksheets也不是任何正确的语法。

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

答案 1 :(得分:0)

这是另一种方式:

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

答案 2 :(得分:0)

我认为您希望将名称添加到工作簿名称集合中。现在的方式是,您仍然必须先参考单个工作表才能访问该名称。

  

工作表(" RoomCode&#34)范围内。(" RoomCode_XYZ&#34)

通过将名称添加到工作簿,无论ActiveSheet如何,您都可以访问该工作簿。

  

范围(" RoomCode_XYZ&#34)

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