简体   繁体   中英

Excel VBA / Sheets.Add.Name Loop throws Error 9

I'm new to Excel VBA and started to build a time tracking workbook for learning. A part of that is a For-Loop which shall add one named worksheet for every month in a year:

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

During Runtime while the loop is adding worksheet after worksheet the MsgBox pops up after every single added sheet with Error 9: "Subscript Out Of Range".

I don't know why this is happening, started reading up quite a bit on the web and still have no solution.. maybe I'm missing something basic, because I'm a beginner.

Please help me.

Thanks in advance!

Please see the below code.

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

I am not sure why you want to avoid having an error. You can probably make a longwinded code for that, but there no use for it. You can also try something shorter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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