Search code examples
excelvba

How to prevent Excel from changing active sheet to newly created sheet


I have a button to create a sheet which works. However, when I create a new sheet with the function, it relocates or redirects me to that new sheet.

I also have a delete button which accepts the sheet name and deletes it instantly with no redirection or relocating.

Is there a way to prevent the redirecting?

Option Explicit

Public sheetName As Variant

Sub AddSheet()
    On Error Resume Next
    sheetName = InputBox("New Sheet Name", "Prototype 01")
    If sheetName = "" Then
        MsgBox "Sheet name cannot be empty!"
        Exit Sub
    End If
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName
    MsgBox "" & sheetName & " was successfully created!"
End Sub

Sub DeleteSheet()
    On Error Resume Next
    sheetName = InputBox("Sheet Name", "Prototype 01")
    If sheetName = "" Then Exit Sub
    Sheets(sheetName).Delete
    MsgBox """" & sheetName & """ was successfully removed!"
End Sub

Solution

  • Yo can switch sheets via Worksheet.Activate function of vba.

    Sheets("YourSheetName").Activate
    

    Once you create the new sheet, add this code to return back to your original sheet.