Excel VBA / Sheets.Add.Name循环抛出错误9

我是新的Excel VBA,并开始build立一个学习时间跟踪工作簿。 其中的一部分是For-Loop,它将在一年的每个月份中添加一个命名工作表:

Sub newyear() Dim month(12) As String Dim i As Integer month(1) = "Januar" month(2) = "Februar" ... month(12) = "Dezember" For i = 1 To 12 On Error Resume Next Sheets.Add(Tabelle1).Name = month(i) MsgBox Err.Number <- this throws Error 9: "Subscript Out Of Range" after every worksheet added during the loop Next i End Sub 

在运行期间,循环在工作表之后添加工作表时,在每个添加的工作表中出现错误9:“下标超出范围”后popupMsgBox。

我不知道为什么会发生这种情况,开始在网上阅读很多,但仍然没有解决scheme..也许我错过了一些基本的东西,因为我是一个初学者。

请帮帮我。

提前致谢!

我不知道为什么要避免出现错误。 你也许可以做一个很长的代码,但没有用处。 你也可以尝试更短的东西:

 Sub newyear() Dim month(12) As String Dim i As Integer month(1) = "January" month(2) = "February" month(3) = "March" month(4) = "April" month(5) = "May" month(6) = "June" month(7) = "July" month(8) = "August" month(9) = "September" month(10) = "October" month(11) = "November" month(12) = "Dezember" On Error Resume Next For i = 1 To 12 If Worksheets(month(i)) Is Nothing Then Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = month(i) End If Next End Sub 

请看下面的代码。

 Sub newyear() On Error Resume Next Dim month(12) As String Dim i As Integer month(1) = "January" month(2) = "February" month(3) = "March" month(4) = "April" month(5) = "May" month(6) = "June" month(7) = "July" month(8) = "August" month(9) = "September" month(10) = "October" month(11) = "November" month(12) = "Dezember" Dim ws As Worksheet For i = 1 To 12 With ThisWorkbook If Worksheets(month(i)).Name <> month(i) Then Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count)) ws.Name = month(i) End If End With If Err.Description <> "" Then Err.Clear 'do what you want to do End If Next i End Sub