使用VBA重命名列表中的多个工作表

时间:2014-01-10 18:56:09

标签: excel excel-vba vba

我是VBA的新手,正在尝试从列表中命名工作表。我有一个包含133个工作表的文件,并希望从其中一个工作表的列表中命名每个工作表。单元格B1至B133具有所需名称的列表,单元格c1至c133具有页面名称(Sheet1至Sheet 133)。我尝试过两种不同的代码无济于事。我错过了什么?

这里是B& B列的摘录。 C看起来像。

File details                    Sheet 1
Sheet Names                     Sheet 23
Calc Notes                      Sheet 2
Rank comparison - baseline      Sheet 3
Trend - Top 30 ct vs baseline   Sheet 5
Trend - Top 30 dur vs baseline  Sheet 6
Trend - Top 30 MTBF vs baseline Sheet 7
Trend - Top 30 ct_dur vs base   Sheet 8
Avail, MTBeF, MTTR scorecard    Sheet 10
Avail, MTBeF, MTTR - Excluded   Sheet 11
All-in vs Excluded              Sheet 12
Summary all lines - count            Sheet 13
Summary all lines - duration    Sheet 14
fault - count                   Sheet 15
fault - duration                Sheet 16
gap count-query vs fault sum    Sheet 17
gap duration-query vs fault sum Sheet 18
missing faults                  Sheet 20
query                           Sheet 9
Prod unit ref                   Sheet 21
Pd Wk ref                       Sheet 22
Query ref                       Sheet 4
FTT                             Sheet 19

#1(运行时错误' 424')

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim x As Integer
Dim y As Integer
Dim z As Integer
x = 1
y = 133

For z = 1 To 133
sheetz.Name = Range(Cells(x, 2), Cells(y, 2))
Next z


End Sub

#2(运行时错误' 91')

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ws As Excel.Worksheet
Dim z As Integer

    For z = 1 To 133
        If ws.Name = Sheetz Then
            Sheetz.Name = Cells(z, 2)
        End If
        Exit For
    Next z

End Sub

3 个答案:

答案 0 :(得分:3)

Sub RenameSheets()
    For i = 1 To 133
        On Error Resume Next
        oldname = Cells(i, 3).Value
        newname = Cells(i, 2).Value
        Sheets(oldname).Name = newname
    Next
End Sub

答案 1 :(得分:2)

请尝试使用此代码:

Sub test()
   On Error Resume Next
   For Each oldName In ThisWorkbook.Workseets("Sheet1").Range("C1:C133")
       ThisWorkbook.Worksheets(oldName.Value).Name = oldName.Offset(0, -1).Value
   Next
End Sub

请注意,您的C1:C133范围应包含不带引号的工作表名称(正确:Sheet1,不正确:"Sheet1"

答案 2 :(得分:1)

可能抛出错误的是Sheetz。表格的索引应在括号中,即Sheet(z)