if statement for sheet not found in workbook

  • Thread starter Thread starter tango
  • Start date Start date
T

tango

dear all,
i want to add new worksheet if the worksheet name is not found in the
workbook when user input in the inputbox.

tosheet is the variable input by user.

** this if statement is incorrect. how should i write the statement?
If Worksheets(tosheet).Name not found in the workbook then

** this line is correct.
Set ws = ThisWorkbook.Worksheets.Add(after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))

End If


thanks alot
 
Sub test()
Dim ws As Worksheet, tosheet As String

tosheet = "this is a test"

With ThisWorkbook.Worksheets
On Error Resume Next
Set ws = .Item(tosheet)
On Error GoTo 0
If ws Is Nothing Then
Set ws = .Add(After:=.Item(.Count))
ws.Name = tosheet
End If
End With
End Sub
 
One way:

Option Explicit
Sub testme()

Dim ToSheet As Worksheet
Dim ToSheetName As String

ToSheetName = InputBox(prompt:="what's the name")
If Trim(ToSheetName) = "" Then
Exit Sub '?
End If

Set ToSheet = Nothing
On Error Resume Next
Set ToSheet = Worksheets(ToSheetName)
On Error GoTo 0

If ToSheet Is Nothing Then
With ThisWorkbook
.Worksheets.Add after:=.Sheets(.Sheets.Count)
End With
Set ToSheet = ActiveSheet
On Error Resume Next
ToSheet.Name = ToSheetName
If Err.Number <> 0 Then
MsgBox "Please rename " & ToSheet.Name & " manually!"
Err.Clear
End If
End If
End Sub
 
try

Sub AddSheetIF()
myname = InputBox("What name")
On Error Resume Next
If worksheets(myname) Is Nothing Then
worksheets.Add.Name = myname
End If
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top