I want a button to copy a template worksheet and ask for the new sheet's name (if the name already exists, it should show an error message).
I'm a beginner so I searched the internet and found the following code from an older post, (VBA - Copy a template worksheet and rename with user entered text):
Sub Test()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Template")
Dim newws As Worksheet, sh As Worksheet, newname
Dim query As Long, xst As Boolean, info As String
retry:
xst = False
newname = Application.InputBox("Enter a new sheet name.", info, , , , , , 2)
If newname = "False" Then Exit Sub
For Each sh In wb.Sheets
If sh.Name = newname Then
xst = True: Exit For
End If
Next
If Len(newname) = 0 Or xst = True Then
info = "Sheet name is invalid. Please retry."
GoTo retry
End If
ws.Copy after:=ws: Set newws = ActiveSheet: newws.Name = newname
End Sub
I tried this code on my home PC (Win10, Excel 2019) and it works perfectly,
But for some reason, on my work PC (Win7, Excel 2007) it does not work properly,
Here's the problem: when user closes the input box, it creates a worksheet called "False",
The next time user opens the input box, it cannot be closed, no matter how many times he clicks on the "cancel" button, and then excel stops working.
Can someone please help me fix this problem, or give me another code to do the same thing?