Excel - Macro to Insert New Worksheet

Asked By Ambe on 23-Aug-07 11:52 AM
Hello-  I have a workbook that contains a macro that formats each new
worksheet that is added.  Before I run the macro, I have to insert & rename
the new worksheet.  I'm wondering if I can add to my existing macro, code
that would automatically insert a new worksheet and rename the worksheet.  My
worksheet names are months of the year, and my worksheet names are just the
months in ascending order for the current year.  I'm sure there is a way to
do this, just don't know what my code would be.

Thanks in advance for any help!




Dave Peterson replied on 23-Aug-07 01:50 PM
One way:

Option Explicit
Sub testme()

Dim TestWks As Worksheet
Dim mCtr As Long
Dim myMonth As String
Dim NextMonth As String

NextMonth = ""
For mCtr = 1 To 12
'xl2002+, IIRC
myMonth = MonthName(mCtr, abbreviate:=False)
'before xl2002
'myMonth = Format(DateSerial(2007, mCtr, 1), "mmmm")

Set TestWks = Nothing
On Error Resume Next
Set TestWks = Worksheets(myMonth)
On Error GoTo 0

If TestWks Is Nothing Then
'this month doesn't exist (yet!)
NextMonth = myMonth
'get out of the loop
Exit For
End If
Next mCtr

If NextMonth = "" Then
MsgBox "All months already exist!"
Else
Worksheets.Add.Name = myMonth
End If

End Sub


--

Dave Peterson
Joe replied on 23-Aug-07 01:52 PM
Sub addmonths()

For MonthCount = 1 To 12


Worksheets.Add after:=Sheets(Sheets.Count)

ActiveSheet.Name = MonthName(MonthCount)
Next MonthCount
End Sub