Macro to Insert New Worksheet

G

Guest

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!
 
D

Dave Peterson

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
 
G

Guest

Sub addmonths()

For MonthCount = 1 To 12


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

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top