如果名称已存在,如何重命名工作表并在名称末尾添加数字。
我使用此代码,但如果名称已存在,则需要在工作表名称的末尾添加一个数字。
VBA_BlankBidSheet.Copy After:=ActiveSheet
ActiveSheet.Name = "New Name"
答案 0 :(得分:2)
下面的代码循环遍历ThisWorkbook
中的所有工作表,并检查是否已存在名称为&#34;新名称&#34;的表单,如果是,则在末尾添加一个数字。< / p>
Sub RenameSheet()
Dim Sht As Worksheet
Dim NewSht As Worksheet
Dim VBA_BlankBidSheet As Worksheet
Dim newShtName As String
' modify to your sheet's name
Set VBA_BlankBidSheet = Sheets("Sheet1")
VBA_BlankBidSheet.Copy After:=ActiveSheet
Set NewSht = ActiveSheet
' you can change it to your needs, or add an InputBox to select the Sheet's name
newShtName = "New Name"
For Each Sht In ThisWorkbook.Sheets
If Sht.Name = "New Name" Then
newShtName = "New Name" & "_" & ThisWorkbook.Sheets.Count
End If
Next Sht
NewSht.Name = newShtName
End Sub
答案 1 :(得分:0)
新工作簿上的测试过程将生成这些工作表名称: Sheet1_1,Sheet2_1和ABC。
如果Sheet1_1存在并且我们要求新的Sheet1它将返回Sheet1_2,因为ABC在新工作簿中不存在它将返回ABC。
测试代码添加了一个名为“DEF”的新工作表。如果再次运行它将创建“DEF_1”。
Sub Test()
Debug.Print RenameSheet("Sheet1")
Debug.Print RenameSheet("Sheet2")
Debug.Print RenameSheet("ABC")
Dim wrkSht As Worksheet
Set wrkSht = Worksheets.Add
wrkSht.Name = RenameSheet("DEF")
End Sub
Public Function RenameSheet(SheetName As String, Optional Book As Workbook) As String
Dim lCounter As Long
Dim wrkSht As Worksheet
If Book Is Nothing Then
Set Book = ThisWorkbook
End If
lCounter = 0
On Error Resume Next
Do
'Try and set a reference to the worksheet.
Set wrkSht = Book.Worksheets(SheetName & IIf(lCounter > 0, "_" & lCounter, ""))
If Err.Number <> 0 Then
'If an error occurs then the sheet name doesn't exist and we can use it.
RenameSheet = SheetName & IIf(lCounter > 0, "_" & lCounter, "")
Exit Do
End If
Err.Clear
'If the sheet name does exist increment the counter and try again.
lCounter = lCounter + 1
Loop
On Error GoTo 0
End Function
修改:删除了Do While bNotExists
,因为我没有检查bNotExists
- 仅使用Exit Do
。
答案 2 :(得分:0)
根据Darren的回答,我认为可以更容易地立即重命名工作表,而不是返回可以使用的名称。我也重构了一下。这是我的看法:
Private Sub nameNewSheet(sheetName As String, newSheet As Worksheet)
Dim named As Boolean, counter As Long
On Error Resume Next
'try to name the sheet. If name is already taken, start looping
newSheet.Name = sheetName
If Err Then
If Err.Number = 1004 Then 'name already used
Err.Clear
Else 'unexpected error
GoTo nameNewSheet_Error
End If
Else
Exit Sub
End If
named = False
counter = 1
Do
newSheet.Name = sheetName & counter
If Err Then
If Err.Number = 1004 Then 'name already used
Err.Clear
counter = counter + 1 'increment the number until the sheet can be named
Else 'unexpected error
GoTo nameNewSheet_Error
End If
Else
named = True
End If
Loop While Not named
On Error GoTo 0
Exit Sub
nameNewSheet_Error:
'add errorhandler here
End Sub
答案 3 :(得分:0)
VB的.net版本使用Try ... Catch公式来捕获运行时错误,请参见{https://msdn.microsoft.com/en-us/library/ms973849.aspx}(https://msdn.microsoft.com/en-us/library/ms973849.aspx)与VB6的旧“ on error”公式进行比较和之前。它更适合做您想做的事,并且可以使更短的异常运行恕我直言。
我试图找出重命名为现有工作表名称时引发的异常,并且在找到该异常时将在此处编辑为可行的脚本。