ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Macro to Insert New Worksheet (https://www.excelbanter.com/excel-programming/396185-macro-insert-new-worksheet.html)

Amber

Macro to Insert New Worksheet
 
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

Macro to Insert New Worksheet
 
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

Amber wrote:

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

joel

Macro to Insert New Worksheet
 
Sub addmonths()

For MonthCount = 1 To 12


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

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


"Amber" wrote:

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!



All times are GMT +1. The time now is 07:47 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com