EXCEL&WPS工作表批量重命名(按照sheet1中A列内容)

将工作表名称批量重命名(按照sheet1中A列内容)

  1. 打开WPS Office的Excel文件。
  2. 按 Alt + F11 打开VBA编辑器。
  3. 在VBA编辑器中,插入一个新模块:点击 插入 -> 模块。
  4. 将以下代码粘贴到模块中:
  5. 运行→运行宏
Sub RenameSheetsBasedOnSheet1()  
    Dim ws As Worksheet  
    Dim sheet1 As Worksheet  
    Dim i As Long, lastRow As Long  
    Dim newName As String  
    Dim nameExists As Boolean  
      
    ' Set the sheet1 worksheet (assuming it's named "Sheet1")  
    Set sheet1 = ThisWorkbook.Sheets("Sheet1")  
      
    ' Find the last row with data in column A of Sheet1  
    lastRow = sheet1.Cells(sheet1.Rows.Count, 1).End(xlUp).Row  
      
    ' Loop through all sheets except Sheet1  
    For Each ws In ThisWorkbook.Sheets  
        If ws.Name <> sheet1.Name Then  
            ' Get the new name from Sheet1's A column  
            i = i + 1  
            If i <= lastRow Then  
                newName = sheet1.Cells(i, 1).Value  
                  
                ' Check if the new name is valid and not already used  
                nameExists = False  
                For Each wks In ThisWorkbook.Sheets  
                    If wks.Name = newName And wks.Name <> ws.Name Then  
                        nameExists = True  
                        Exit For  
                    End If  
                Next wks  
                  
                If newName <> "" And Not nameExists Then  
                    ' Rename the sheet  
                    On Error Resume Next ' In case of any error (e.g., invalid sheet name)  
                    ws.Name = newName  
                    If Err.Number <> 0 Then  
                        MsgBox "Error renaming sheet to " & newName & ": " & Err.Description, vbCritical  
                        Err.Clear  
                    End If  
                    On Error GoTo 0 ' Reset error handling  
                Else  
                    If newName = "" Then  
                        MsgBox "Empty name found in Sheet1 A" & i & ". Skipping this rename.", vbExclamation  
                    Else  
                        MsgBox "Name """ & newName & """ already exists. Skipping this rename.", vbExclamation  
                    End If  
                End If  
            Else  
                Exit For ' No more names to assign  
            End If  
        End If  
    Next ws  
      
    MsgBox "Sheets have been renamed based on Sheet1 A column where possible.", vbInformation  
End Sub
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

歌颂平凡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值