VBA - Worksheet creation

oggy3000

Board Regular
Joined
Jul 13, 2011
Messages
51
Hey,
with the following code I am creating a new worksheet.

Code:
Private Sub cmdCreate_Click()
Dim intInlength, intOutlength, intMonth, intYear As Integer
intMonth = cboMonth.Value

Worksheets("Cost Temp").Copy After:=Sheets(Worksheets.Count)

With ActiveSheet
  .Name = cboMonth.Value & "-" & cboYear.Value
  .Range("C1") = cboMonth.Value
  .Range("D1") = cboYear.Value
End With

End Sub

However, I want it to overwrite existing sheets with the same name. How can I do that?

Jan
 

Excel Facts

Is there a shortcut key for strikethrough?
Ctrl+S is used for Save. Ctrl+5 is used for Strikethrough. Why Ctrl+5? When you use hashmarks to count |||| is 4, strike through to mean 5.
Perhaps that would be deleting old and renaming new?

1. Name new sheet with "temp' name
2. Delete "old" sheet
3. Rename "temp" name sheet with "old" sheet name
 
Upvote 0
Jan

Only lightly tested:
Code:
Option Explicit
 
Private Sub cmdCreate_Click()
Dim wsNew As Worksheet
Dim strNewName As String
Dim intInlength As Long, intOutlength As Long, intMonth As Long, intYear As Long

    intMonth = cboMonth.Value
    Worksheets("Cost Temp").Copy After:=Sheets(Worksheets.Count)

    strNewName = cboMonth.Value & "-" & cboYear.Value

    Set wsNew = ActiveSheet
 
    Application.DisplayAlerts = False

    On Error Resume Next
    Worksheets(strNewName).Delete
    On Error GoTo 0

    Application.DisplayAlerts = True

    With wsNew
        .Name = strNewName
        .Range("C1") = cboMonth.Value
        .Range("D1") = cboYear.Value
    End With
 
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,609
Messages
6,179,879
Members
452,948
Latest member
Dupuhini

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top