重命名特定的工作表选项卡

时间:2018-12-29 17:17:10

标签: excel vba

我的目标是控制要重命名的工作表选项卡。

Sub RenameSheets()
    Dim I As Long
    On Error Resume Next
    xTitleld = "Rename Worksheets"
    newName = Application.InputBox("Name",xTitleld,"",Type:=2)
    For i = 1 To Application.Sheets.Count
        If Sheets(i).Name <>"Signature" AND WS.Name <> "Invoice" AND WS.Name `<> "Cover" _ 
           Then Sheeets (i).Name = newName & i
    Next
End Sub

我希望更改名为AR1,AR2等的工作表标签。

工作簿中还有许多其他表格。该代码正在更改所有工作表标签。

3 个答案:

答案 0 :(得分:0)

尝试此代码

Sub RenameSheets()
Dim i As Long
Dim xTitleld As String
Dim newName As String
Dim ws As Worksheet
    'On Error Resume Next
    xTitleld = "Rename Worksheets"
    newName = Application.InputBox("Name", xTitleld, "", Type:=2)
    For i = 1 To Application.Sheets.Count
        Set ws = Sheets(i)
        If ws.Name <> "Signature" And ws.Name <> "Invoice" And ws.Name <> "Cover" Then
            Sheets(i).Name = newName & i
        End If
    Next
End Sub

答案 1 :(得分:0)

您可以尝试使用Select Case ThisWorkbook.Sheets(i).Name,它将大大简化和缩短您的代码。您将来也可以添加更多名称。

修改后的代码

Option Explicit

Sub RenameSheets()

Dim i As Long
Dim newName As String, xTitleld As String

xTitleld = "Rename Worksheets"
newName = Application.InputBox("Name", xTitleld, "", Type:=2)

For i = 1 To ThisWorkbook.Sheets.Count
    Select Case ThisWorkbook.Sheets(i).Name
        Case "Signature", "Invoice", "Cover"
            ' Do Nothing                
        Case Else
            ThisWorkbook.Sheets(i).Name = newName & i        
    End Select
Next i

End Sub

答案 2 :(得分:0)

You can test whether the characters "AR" appear at the beginning of the name.

Option Explicit

Sub RenameSheets_AR()

    Dim I As Long
    Dim xTitleld As String
    Dim newName  As String

    ' Use only in specific circumstances
    'On Error Resume Next
    ' To increase debugging success see http://www.cpearson.com/excel/errorhandling.htm

    xTitleld = "Rename Worksheets"

keyName:
    newName = Application.InputBox("Name", xTitleld, "", Type:=2)

    If newName = "" Then Exit Sub

    For I = 1 To Application.Sheets.Count
        If Left(Sheets(I).Name, 2) = "AR" Then
            Sheets(I).Name = newName & I
        End If
    Next

End Sub