使用 VBA 宏重命名 Excel 工作表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36346866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:19:41  来源:igfitidea点击:

Rename Excel Sheet with VBA Macro

excelvbaexcel-vba

提问by Ongok Ongoksepen

I want to ask about rename the excel sheet, i want to rename the sheet with new name : older name + _v1.

我想问一下重命名excel表格,我想用新名称重命名表格:旧名称+ _v1。

So if my current sheet name is test, then I want the new name test_v1.

因此,如果我当前的工作表名称是test,那么我想要新名称test_v1

I only know the standard vba for rename excel sheet which is renaming excel sheet by the sheet content.

我只知道重命名 Excel 工作表的标准 vba,它通过工作表内容重命名 Excel 工作表。

Sub Test()

Dim WS As Worksheet

For Each WS In Sheets
   WS.Name = WS.Range("A5")
Next WS
End Sub

回答by Realitybites

The "no frills" options are as follows:

“无装饰”选项如下:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

您还可以查看录制宏并查看它为您提供的代码,这是开始学习一些更普通的功能的好方法。

回答by Tim Williams

This should do it:

这应该这样做:

WS.Name = WS.Name & "_v1"

回答by brettdj

Suggest you add handling to test if any of the sheets to be renamed already exist:

建议您添加处理以测试任何要重命名的工作表是否已存在:

Sub Test()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String

On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
    If ws1 Is Nothing Then
        ws.Name = ws.Name & "_v1"
    Else
         strErr = strErr & ws.Name & "_v1" & vbNewLine
    End If
Set ws1 = Nothing
Next
On Error GoTo 0

If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"

End Sub