Hi,
I am facing an issue with a code. I am a beginer and practicing with writing small codes. I just want to insert a worksheet with desired sheet name.
I wrote this code to work like this: if at first time, I don't enter any name or click on "cancel" button, it run macro again and ask for a name, if I enter a name, it should check if there isn't an existing sheet with this name. when both tests are clear it add a new worksheet with entered name.
When I enter a name at first instance, it is not giving any error and working well. However, if at first instance, I don't enter any name or click on cancel button then it is giving me an error and exicuting code even after exicuting "end sub".
Code is mentioned below:
Sub AddNewSheet()
Dim ws As Worksheet
Dim sname As String
sname = Application.InputBox("Enter desired Sheet Name", "InputBox", , , , , , 2)
If sname = vbNullString Or sname = "False" Then
MsgBox "Please enter a name"
Run "addnewsheet"
End If
For Each ws In ActiveWorkbook.Sheets
If ws.Name = sname Then
MsgBox "Sheet with this name exists, please enter a unique name"
Run "addnewsheet"
End If
Next ws
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = sname
End Sub
Please help.
DJ
I am facing an issue with a code. I am a beginer and practicing with writing small codes. I just want to insert a worksheet with desired sheet name.
I wrote this code to work like this: if at first time, I don't enter any name or click on "cancel" button, it run macro again and ask for a name, if I enter a name, it should check if there isn't an existing sheet with this name. when both tests are clear it add a new worksheet with entered name.
When I enter a name at first instance, it is not giving any error and working well. However, if at first instance, I don't enter any name or click on cancel button then it is giving me an error and exicuting code even after exicuting "end sub".
Code is mentioned below:
Sub AddNewSheet()
Dim ws As Worksheet
Dim sname As String
sname = Application.InputBox("Enter desired Sheet Name", "InputBox", , , , , , 2)
If sname = vbNullString Or sname = "False" Then
MsgBox "Please enter a name"
Run "addnewsheet"
End If
For Each ws In ActiveWorkbook.Sheets
If ws.Name = sname Then
MsgBox "Sheet with this name exists, please enter a unique name"
Run "addnewsheet"
End If
Next ws
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = sname
End Sub
Please help.
DJ