简体   繁体   English

添加带有连续编号VBA的工作表

[英]Add sheet with successive number VBA

I have a simple macro, that adds a sheet to a workbook. 我有一个简单的宏,可以在工作簿中添加工作表。 However, sometimes I have to delete some sheet(s). 但是,有时我必须删除一些工作表。 When I delete a sheet and I use the macro again, the newly added sheet assumes the number which follows, as if the deleted sheets are stil present. 当我删除工作表并再次使用宏时,新添加的工作表将采用后面的数字,好像删除的工作表仍然存在。 I want that the macro adds a sheet with the next number. 我希望宏添加带有下一个数字的工作表。 For example I have: 例如,我有:

Sheet1 Sheet2 Sheet3

Then I delete Sheet3 and want to add another sheet, which perfectly will be Sheet3 and not Sheet4 然后我删除Sheet3并要添加另一个表,完全是Sheet3而不是Sheet4

With ThisWorkbook

    .Sheets.add After:=.Sheets(.Sheets.Count)

End With

How can I do this? 我怎样才能做到这一点?

Add this code in the Workbook: 在工作簿中添加以下代码: 在此处输入图片说明

Option Explicit

Private Sub Workbook_NewSheet(ByVal Sh As Object)

    On Error GoTo Workbook_NewSheet_Error

    Sh.Name = "Sheet" & Sheets.Count

    On Error GoTo 0
    Exit Sub

Workbook_NewSheet_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Workbook_NewSheet of VBA Document DieseArbeitsmappe"

End Sub

Pretty much, if you have a the following sheets Sheet1 , Sheet2 and Sheet4 and you add a new one you would get an error, because the name of the sheet is taken ( Sheet4 ). 差不多,如果您有以下工作表Sheet1Sheet2Sheet4然后添加一个新工作Sheet4 ,则会出错,因为工作表的名称已被提取( Sheet4 )。 That is why I have added error handler. 这就是为什么我添加了错误处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM