How to call another function within a function in VBA - excel

I'm currently trying to detect duplicated sheet name using "CheckSheet" function. And I want to call this function to run in "Add Sheet" to prevent users from creating duplicate sheet names. However, I ran into error "Compile Error: Expected function or variable" and still not succeeding in solving the problem. Kindly enlighten me where I am doing it wrong and feel free to point out if there are any weakness and better optimization to my code. Thanks in advance.
Option Explicit
Public sheetName As Variant
Public cS As Variant
Sub CheckSheet(cS) 'To check duplicate sheet name - used in AddSheet function.
Dim wS As Worksheet
Dim wsName As String
wsName = wS(sheetName)
On Error GoTo 0
If wS Is Nothing Then
cS = False
Exit Sub
End Sub
Sub AddSheet()
Dim cSheet As Variant
cSheet = CheckSheet(cS).Value
On Error Resume Next
sheetName = Application.InputBox(prompt:="New Sheet Name", Left:=(Application.Width / 2), Top:=(Application.Height / 2), Title:="Add Sheet", Type:=2)
If sheetName = "" Then
MsgBox "Sheet name cannot be empty!"
Exit Sub
ElseIf cSheet = False Then
MsgBox "Duplicate Name! Please try again!"
Exit Sub
Else
Application.ScreenUpdating = False
Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName
MsgBox """" & sheetName & """ was successfully created!"
Sheets("Sheet1").Activate
End If
End Sub

Two things.
1. Your code can be simplified. You do not need a function to check if a worksheet exists.
Option Explicit
Sub AddSheet()
Dim sh As Object
Dim sheetName As Variant
'~~> Accept user input
sheetName = Application.InputBox(prompt:="New Sheet Name", _
Left:=(Application.Width / 2), _
Top:=(Application.Height / 2), _
Title:="Add Sheet", Type:=2)
'~~> User presses cancel
If sheetName = False Then Exit Sub
'~~> Check if the sheet name is empty
If sheetName = "" Then
MsgBox "Sheet name cannot be empty!"
Exit Sub
End If
'~~> Check if the sheet exists
On Error Resume Next
Set sh = ThisWorkbook.Sheets(sheetName)
On Error GoTo 0
If Not sh Is Nothing Then
MsgBox "Duplicate Name! Please try again!"
Exit Sub
End If
'~~> Create the worksheet
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = sheetName
MsgBox """" & sheetName & """ was successfully created!"
End With
End Sub
2. Even if you want to use a function, your code has lot of errors. (One of them is pointed out by #braX above.
Is this what you are trying?
Option Explicit
Sub AddSheet()
Dim sheetName As Variant
'~~> Accept user input
sheetName = Application.InputBox(prompt:="New Sheet Name", _
Left:=(Application.Width / 2), _
Top:=(Application.Height / 2), _
Title:="Add Sheet", Type:=2)
'~~> User presses cancel
If sheetName = False Then Exit Sub
'~~> Check if the sheet name is empty
If sheetName = "" Then
MsgBox "Sheet name cannot be empty!"
Exit Sub
End If
'~~> Check if the sheet exists
If DoesSheetExists(CStr(sheetName)) = True Then
MsgBox "Duplicate Name! Please try again!"
Exit Sub
End If
'~~> Create the worksheet
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = sheetName
MsgBox """" & sheetName & """ was successfully created!"
End With
End Sub
'~~> Function to check if sheet exists
Private Function DoesSheetExists(wsName As String) As Boolean
Dim sh As Object
'~~> Check if the sheet exists
On Error Resume Next
Set sh = ThisWorkbook.Sheets(wsName)
On Error GoTo 0
If Not sh Is Nothing Then DoesSheetExists = True
End Function

Related

How to prevent excel from relocating or changing active sheet to newly created sheet after creating a new sheet via function button

I have created a button that would create a new sheet which works just fine. However, when I created a new sheet with the function, it relocates or redirect me to that new sheet which make. I also have a delete button in which it just accepts the sheet name and delete it instantly with no redirection or relocating. Is there a way to prevent the redirecting from happening? I am still a beginner so if I am doing something wrong, pls kindly correct me! Thanks in advance.
Here is the code.
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
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.
Add a Worksheet or Delete a Sheet
It is assumed that the delete code will be called by a button so the active sheet (the one with the button) cannot accidentally be deleted.
Add
Option Explicit
Sub AddSheet()
Const PROC_TITLE As String = "Add Sheet"
If ActiveSheet Is Nothing Then Exit Sub ' no visible workbooks open
If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
Dim aws As Worksheet: Set aws = ActiveSheet
Dim wb As Workbook: Set wb = aws.Parent
Dim SheetName As String
SheetName = InputBox("Enter name of sheet to be ADDED", PROC_TITLE)
If Len(SheetName) = 0 Then
MsgBox "Sheet name cannot be empty!", _
vbCritical, PROC_TITLE
Exit Sub
End If
Dim nws As Worksheet
Set nws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
Dim ErrNum As Long
On Error Resume Next ' invalid or existing sheet name
nws.Name = SheetName
ErrNum = Err.Number
On Error GoTo 0
Dim IsSuccess As Boolean
If ErrNum = 0 Then
IsSuccess = True
Else
Application.DisplayAlerts = False
nws.Delete
Application.DisplayAlerts = True
End If
aws.Select
If IsSuccess Then
MsgBox "Worksheet """ & SheetName & """ successfully added.", _
vbInformation, PROC_TITLE
Else
MsgBox "Could not rename to """ & SheetName & """.", _
vbCritical, PROC_TITLE
End If
End Sub
Delete
Sub DeleteSheet()
Const PROC_TITLE As String = "Delete Sheet"
If ActiveSheet Is Nothing Then Exit Sub ' no visible workbooks open
If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
Dim aws As Worksheet: Set aws = ActiveSheet
Dim wb As Workbook: Set wb = aws.Parent
Dim SheetName As String
SheetName = InputBox("Enter name of sheet to be DELETED", PROC_TITLE)
If Len(SheetName) = 0 Then
MsgBox "Sheet name cannot be empty!", _
vbCritical, PROC_TITLE
Exit Sub
End If
Dim dsh As Object ' allowing charts to be deleted
On Error Resume Next
Set dsh = wb.Sheets(SheetName)
On Error Resume Next
If dsh Is Nothing Then
MsgBox "There is no sheet named """ & SheetName & """!", _
vbCritical, PROC_TITLE
Exit Sub
End If
' Don't delete the ActiveSheet, the one with the buttons.
If dsh Is aws Then
MsgBox "Cannot delete the 'button' worksheet """ & aws.Name & """!", _
vbCritical, PROC_TITLE
Exit Sub
End If
' A very hidden sheet cannot be deleted. There is no error though.
If dsh.Visible = xlSheetVeryHidden Then
MsgBox "Cannot delete the very hidden sheet """ & SheetName & """!", _
vbCritical, PROC_TITLE
Exit Sub
End If
Application.DisplayAlerts = False
dsh.Delete
Application.DisplayAlerts = True
aws.Select
MsgBox "Sheet """ & SheetName & """ successfully deleted.", _
vbInformation, PROC_TITLE
End Sub

Microsoft Excel VBA Intersect with Rename Sheet

I'm trying to change the name of a sheet after it is created under and Intersect method. The code I have below give Error 424. The code works when only creating a new sheet.
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Set Active_Range = Range("B6:F11")
If Not Application.Intersect(Target, Active_Range) Is Nothing Then
Sheets("Employee Details").Copy after:=Sheets("Job Schedule")
Sheets("Employee Details (2)").Name.Value = "Name One"
End If
End Sub
I have tried creating a trigger for the workbook that renames the new sheet when it is created but that does not work either.
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Sh.Name.Value = "Name One"
End Sub
Is this what you are trying? (Not fully tested)
Option Explicit
Private Sub Workbook_NewSheet(ByVal Sh As Object)
'~~> This is the name that you want to give
Dim Nm As String
Nm = "Name One"
'~~> Check if this name is already taken
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Sheets(Nm)
On Error GoTo 0
If Not ws Is Nothing Then
'~~> Name the new worksheet
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = Nm
Else
'~~> Alert user and delete the newly created sheet
MsgBox "This name is already taken"
Application.DisplayAlerts = False
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Delete
Application.DisplayAlerts = True
End If
End Sub
sticking to your "Workbook_NewSheet" approach
in any Module code pane, put this at the very top
Option Private Module ' make the Public variables "local" to current VBA project only
Public newSheetName As String ' this variable will be available to any other Sub, Function of this Project
in ThisWorkbook code pane, put this
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Sh.Name = newSheetName
End Sub
in your relevant Worksheet code pane, put this
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Dim Active_Range As Range
Set Active_Range = Range("B6:F11")
If Not Application.Intersect(Target, Active_Range) Is Nothing Then
newSheetName = "Name One" ' set the public variable
Sheets("Employee Details").Copy after:=Sheets("Job Schedule")
End If
End Sub
After that, you may want to add code (I'd do that in "Workbook_NewSheet()" to ensure the new worksheet name:
a) matches the sheet name rules
b) isn't already used for another sheet in the same workbook
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Dim Active_Range As Range
Set Active_Range = Range("B6:F11")
If Not Application.Intersect(Target, Active_Range) Is Nothing Then
Name2 = ActiveCell().Value
Sheets("Employee Details").Copy After:=Sheets("Job Schedule")
Worksheets("Employee Details (2)").Name = "Employee Details - " + Name2
End If
End Sub
Above is what I came up with after digging and reading a little more.
A Worksheet BeforeRightClick: Copy and Rename Template Worksheet
Sheet Module e.g. Sheet1
Option Explicit
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
AddNewEmployeeDetails Target, Cancel
End Sub
Standard Module e.g. Module1
Option Explicit
Sub AddNewEmployeeDetails(ByVal Target As Range, ByRef Cancel As Boolean)
Const PROC_TITLE As String = "Add New Employee Details Sheet"
Const TARGET_RANGE As String = "B6:F11"
Const SRC_SHEET_NAME As String = "Employee Details"
Const AFTER_SHEET_NAME As String = "Job Schedule"
Const DST_SHEET_NAME_PREFIX As String = "Employee Details - "
Dim tws As Worksheet: Set tws = Target.Worksheet
Dim trg As Range: Set trg = Intersect(tws.Range(TARGET_RANGE), Target)
If trg Is Nothing Then Exit Sub
Dim eName As String: eName = CStr(Target.Value) ' for the message boxes
Dim dName As String: dName = DST_SHEET_NAME_PREFIX & eName
Dim wb As Workbook: Set wb = tws.Parent
Dim dsh As Object
On Error Resume Next ' to prevent error if sheet doesn't exist
Set dsh = wb.Sheets(dName)
On Error GoTo 0
If dsh Is Nothing Then ' sheet doesn't exist
Dim sws As Worksheet: Set sws = wb.Sheets(SRC_SHEET_NAME)
Dim aws As Worksheet: Set aws = wb.Sheets(AFTER_SHEET_NAME)
sws.Copy After:=aws
Dim dws As Worksheet: Set dws = aws.Next
Dim ErrNumber As Long, ErrDescription As String
On Error Resume Next ' to prevent error if invalid sheet name
dws.Name = dName
ErrNumber = Err.Number
ErrDescription = Err.Description
On Error GoTo 0
If ErrNumber <> 0 Then ' sheet name is invalid
Application.DisplayAlerts = False ' to delete without confirmation
dws.Delete
Application.DisplayAlerts = True
tws.Select
MsgBox "Run-time error '" & ErrNumber & "':" & vbLf & vbLf _
& ErrDescription & vbLf & vbLf & "Could not rename to """ _
& dName & """.", vbCritical, PROC_TITLE
Else ' sheet name is valid
MsgBox "Employee Details sheet for " & eName & " added.", _
vbInformation, PROC_TITLE
End If
Else ' sheet exists
MsgBox "The Employee Details sheet for " & eName _
& " already exists.", vbCritical, PROC_TITLE
End If
Cancel = True
End Sub

Check sheet name and run the code related to the sheet

I' am looking for a code to check Sheet names initially like A, B, C. If sheet A exist then it should run the code which is goto A1: else it should go to B and check if Sheet B exist, if sheet B exist then it should run code below B1, Same way for sheet C as well.
Ex:
For I = 1 to worksheets.count
If Sheets(i).Name = "A" Then
GoTo A1
Else
GoTo B
End If
Next I
I think it can be solved by using ElseIf or Select Case.
Please try with the following 2 cases.
Dim i As Integer
For i = 1 To Worksheets.Count
Select Case Sheets(i).Name
Case "A"
' Coding for "GoTo A1"
Case "B"
' Coding for "GoTo B1"
Case "C"
' Coding for "GoTo C1"
...
End Select
Next i
Or
Dim i As Integer
For i = 1 To Worksheets.Count
If Sheets(i).Name = "A" Then
' Coding for "GoTo A1"
ElseIf Sheets(i).Name = "B" Then
' Coding for "GoTo B1"
ElseIf Sheets(i).Name = "C" Then
' Coding for "GoTo C1"
Else
...
End If
Next i
If you have a specific macro you want to run on each sheet and you want to trigger all of them to run at once, you can organize it like so:
Sub Main()
Call SheetA_Macro
Call SheetB_Macro
Call SheetC_Macro
End Sub
If you have a lot of sheets you can automate the calling of these macros by naming them all the same thing and placing them into the sheet's code module, which would let you call them in this way:
Sub Main()
Dim Sht As Worksheet
For Each Sht In ThisWorkbook.Worksheets
Call ThisWorkbook.Sheets(Sht.Name).MySheetSpecificMacro
Next Sht
End Sub
If you have an unknown sheet and you want to call only that specific sheets macro, then you will want to do it like above but without the loop.
Call ThisWorkbook.Sheets(MyUnknownSheetObject.Name).MySheetSpecificMacro
Remember that the macros must be placed into the sheet's code module and should all be named the same thing.
Worksheet Related Code
Writes the list of worksheet names to an array.
Loops through the array attempting to find an existing worksheet using the WorksheetExists function.
Continues with the worksheet that exists (if any).
Option Explicit
Sub ApplyToFirstFound()
Const wsNamesList As String = "A,B,C"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim wsNames() As String: wsNames = Split(wsNamesList, ",")
Dim wsName As String
Dim n As Long
For n = 0 To UBound(wsNames)
If WorksheetExists(wb, wsNames(n)) Then
wsName = wsNames(n)
Exit For
End If
Next n
' You could continue with...
If n > UBound(wsNames) Then
MsgBox "No worksheet exists.", vbCritical, "ApplyToFirstFound"
Exit Sub
End If
MsgBox "The first found worksheet is named '" & wsName & "'.", _
vbInformation, "ApplyToFirstFound"
' ... continue...
' ... or with a different code for each worksheet (I've used the same.).
Select Case wsName
Case "A"
MsgBox "Applying to '" & wsName & "'.", _
vbInformation, "ApplyToFirstFound"
Case "B"
MsgBox "Applying to '" & wsName & "'.", _
vbInformation, "ApplyToFirstFound"
Case "C"
MsgBox "Applying to '" & wsName & "'.", _
vbInformation, "ApplyToFirstFound"
Case Else
MsgBox "No worksheet exists.", vbCritical, "ApplyToFirstFound"
End Select
End Sub
Function WorksheetExists( _
ByVal wb As Workbook, _
ByVal WorksheetName As String) _
As Boolean
On Error GoTo ClearError
Dim ws As Worksheet: Set ws = wb.Worksheets(WorksheetName)
WorksheetExists = Not ws Is Nothing
Exit Function
ClearError:
Resume Next
End Function

Silently VBA add new Excel worksheet without screen update

I'm adding a new worksheet to my workbook with
Application.ScreenUpdating = False
SheetExists = False
For Each WS In Worksheets
If WS.Name = "BLANK" Then
SheetExists = True
End If
Next WS
If Not SheetExists Then
Sheets.Add
ActiveSheet.Name = "BLANK"
End If
Is there any way to sheets.add silently without bringing focus to or activating the new added sheet? I just want to stay on the sheet (ie. Sheet1) that is currently active and add the new sheet in the background.
Thanks
At first, things look simple but there are a few things to consider:
There could be more sheets selected before running the code
The selected sheet(s) could be Chart sheet(s)
The Workbook can be protected
You might not want to set Application.ScreenUpdating = True at the end of the method because you might be running this from within another method that still needs it off
Restoring selection can only happen if the proper window is activated
You could use this method:
Sub AddWorksheet(ByVal targetBook As Workbook, ByVal sheetname As String)
Const methodName As String = "AddWorksheet"
'Do input checks
If targetBook Is Nothing Then
Err.Raise 91, methodName, "Target Book not set"
ElseIf sheetname = vbNullString Then
Err.Raise 5, methodName, "Sheet name cannot be blank"
ElseIf Len(sheetname) > 31 Then
Err.Raise 5, methodName, "Sheet name cannot exceed 31 characters"
Else
Dim arrForbiddenChars() As Variant
Dim forbiddenChar As Variant
arrForbiddenChars = Array(":", "\", "/", "?", "*", "[", "]")
For Each forbiddenChar In arrForbiddenChars
If InStr(1, sheetname, forbiddenChar) > 0 Then
Err.Raise 5, methodName, "Sheet name cannot contain characters: : \ / ? * [ or ]"
End If
Next forbiddenChar
End If
Dim alreadyExists As Boolean
'Check if a sheet already exists with the desired name
On Error Resume Next
alreadyExists = Not (targetBook.Sheets(sheetname) Is Nothing)
On Error GoTo 0
If alreadyExists Then
MsgBox "A sheet named <" & sheetname & "> already exists!", vbInformation, "Cancelled" 'Can remove
Exit Sub
End If
'Check if Workbook is protected
If targetBook.ProtectStructure Then
'Maybe write code to ask for password and then unprotect
'
'
'Or simply exit
MsgBox "Workbook is protected. Cannot add sheet", vbInformation, "Cancelled"
Exit Sub
End If
Dim bookActiveWindow As Window
Dim appActiveWindow As Window
Dim selectedSheets As Sheets
Dim screenUpdate As Boolean
Dim newWSheet As Worksheet
'Store state
Set bookActiveWindow = targetBook.Windows(1)
Set appActiveWindow = Application.ActiveWindow 'Can be different from the target book window
Set selectedSheets = bookActiveWindow.selectedSheets
screenUpdate = Application.ScreenUpdating
'Do main logic
screenUpdate = False
If bookActiveWindow.Hwnd <> Application.ActiveWindow.Hwnd Then
bookActiveWindow.Activate
End If
If selectedSheets.Count > 1 Then selectedSheets(1).Select Replace:=True
Set newWSheet = targetBook.Worksheets.Add
newWSheet.Name = sheetname
'Restore state
selectedSheets.Select Replace:=True
If appActiveWindow.Hwnd <> Application.ActiveWindow.Hwnd Then
appActiveWindow.Activate
End If
Application.ScreenUpdating = screenUpdate
End Sub
If you want the book containing the code then you can call with:
Sub Test()
AddWorksheet ThisWorkbook, "BLANK"
End Sub
or, if you want the currently active book (assuming you are running this from an add-in) then you can call with:
Sub Test()
AddWorksheet ActiveWorkbook, "BLANK"
End Sub
or any other book depending on your needs.
Just remember who was active:
Sub ytrewq()
Dim wsh As Worksheet, SheetsExist As Boolean
Set wsh = ActiveSheet
Application.ScreenUpdating = False
SheetExists = False
For Each ws In Worksheets
If ws.Name = "BLANK" Then
SheetExists = True
End If
Next ws
If Not SheetExists Then
Sheets.Add
ActiveSheet.Name = "BLANK"
End If
wsh.Activate
Application.ScreenUpdating = False
End Sub

How to add a named sheet at the end of all Excel sheets?

I am trying to add an Excel sheet named "Temp" at the end of all existing sheets, but this code is not working:
Private Sub CreateSheet()
Dim ws As Worksheet
ws.Name = "Tempo"
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
End Sub
Can you please let me know why?
Try this:
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Tempo"
End Sub
Or use a With clause to avoid repeatedly calling out your object
Private Sub CreateSheet()
Dim ws As Worksheet
With ThisWorkbook
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
ws.Name = "Tempo"
End With
End Sub
Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.
Sub CreateSheet()
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
End With
End Sub
Kindly use this one liner:
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"
ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"
(when you add a worksheet, anyway it'll be the active sheet)
Try this:
Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
On Error GoTo the_dark
Dim wsSheet As Worksheet
Dim bFoundWS As Boolean
bFoundWS = False
If inNamePrefix <> "" Then
Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
End If
If inBeforeOrAfter = iAfter Then
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
Else
Worksheets.Add(After:=wsSheet).Name = inName
End If
Else
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(Before:=Worksheets(1)).Name = inName
Else
Worksheets.Add(Before:=wsSheet).Name = inName
End If
End If
Set addSheet = findWS(inWB, inName, bFoundWS) ' just to confirm it exists and gets it handle
the_light:
Exit Function
the_dark:
MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
Err.Clear
GoTo the_light
End Function
Try to use:
Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"
If you want to check whether a sheet with the same name already exists, you can create a function:
Function funcCreateList(argCreateList)
For Each Worksheet In ThisWorkbook.Worksheets
If argCreateList = Worksheet.Name Then
Exit Function ' if found - exit function
End If
Next Worksheet
Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function
When the function is created, you can call it from your main Sub, e.g.:
Sub main
funcCreateList "MySheet"
Exit Sub
Try switching the order of your code. You must create the worksheet first in order to name it.
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = "Tempo"
End Sub
thanks,
This will give you the option to:
Overwrite or Preserve a tab that has the same name.
Place the sheet at End of all tabs or Next to the current tab.
Select your New sheet or the Active one.
Call CreateWorksheet("New", False, False, False)
Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
activeSheetNumber = Sheets(ActiveSheet.Name).Index
If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
If (preserveOldSheet) Then
MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
Exit Sub
End If
Application.DisplayAlerts = False
Worksheets(sheetName).Delete
End If
If (isLastSheet) Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
Else 'Place sheet after the active sheet.
Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
End If
If (selectActiveSheet) Then
Sheets(activeSheetNumber).Activate
End If
End Sub
This is a quick and simple add of a named tab to the current worksheet:
Sheets.Add.Name = "Tempo"

Resources