All About Worksheets: Add New Worksheet With Name
All About Worksheets: Add New Worksheet With Name
All About Worksheets: Add New Worksheet With Name
The code below shows how you can create a new Worksheet and give it a name. Note that with Add the new sheet
always becomes the active sheet.
Dim wb As Workbook: Set wb =
Dim strName As String: strName =
Dim ws As Worksheet
Set ws = wb.Worksheets.Add(Type:=xlWorksheet)
With ws
.Name = strName
End With
The below sections discuss the arguments you can use to control how worksheets are added with specified
position: Before and After, Count and what Type possibly using a template Template. At the end there is a macro you
can use to Insert sheet with name specified by the user.
An object that specifies the sheet Before or After which the new sheet is added. If Before and After are both omitted, the
new sheet is inserted before the active sheet.
As an example, below code adds a new worksheet After the active sheet in the active workbook
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets.Add(Type:=xlWorksheet, After:=Application.ActiveSheet)
Set ws = wb.Worksheets.Add(Before:=wb.Worksheets(1), Type:=xlWorksheet)
Set ws = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count), Type:=xlWorksheet)
Count
Type
Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet or xlChart - or template file
path. The default value is xlWorksheet.
Use Template
You can also insert sheets based on an existing template, see below.
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim ws As Worksheet
Dim strTemplate As String: strTemplate = "C:\temp\tpt.xlsx"
Set ws = wb.Sheets.Add(Type:=strTemplate)
a MsgBox informs the user about any problems and lets the user either Abort or Retry.
Sub AddNewWorksheet()
Const cstrTitle As String = "Add new worksheet"
Const cstrPrompt As String = "Give the name for the new worksheet." & vbCrLf & "Not
allowed are the characters: : \ / ? * [ and ]"
Dim strInput As String
Dim strDefault As String: strDefault = "" 'setting initial value for inputbox can be
useful
Dim strInputErrorMessage As String
Dim booValidatedOk As Boolean: booValidatedOk = False
On Error GoTo HandleError
Do
strInput = InputBox(Prompt:=cstrPrompt, Title:=cstrTitle, Default:=strDefault)
If Len(strInput) = 0 Then GoTo HandleExit
GoSub ValidateInput
If Not booValidatedOk Then
If vbCancel = MsgBox(strInputErrorMessage & "Retry?", vbExclamation + vbOKCan
cel) Then GoTo HandleExit
End If
Loop While Not booValidatedOk
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim shts As Sheets: Set shts = wb.Sheets
Dim obj As Object
Set obj = shts.Add(Before:=ActiveSheet, Count:=1, Type:=XlSheetType.xlWorksheet)
obj.Name = strInput
HandleExit:
Exit Sub
HandleError:
MsgBox Err.Description
Resume HandleExit
ValidateInput:
If SheetExists(strSheetName:=strInput) Then
strInputErrorMessage = "Sheet already exists. "
ElseIf Not IsValidSheetName(strSheetName:=strInput) Then
strInputErrorMessage = "Sheetname not allowed. "
Else
booValidatedOk = True
End If
Return
End Sub
Dim wb As Workbook: Set wb =
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet2")
ws.Activate
Dim wb As Workbook: Set wb =
wb.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
With Activate, if you presently have more than one sheet selected, the ActiveSheet will change, but all selected sheets will remain selected.
With Select, the selected sheet becomes the ActiveSheet. If more sheets are selected (as above), the first in the array is made active sheet.
Copy a worksheet
The Copy method of the Worksheet object copies the sheet and its contents into an open or new workbook.
Notes
The copied worksheet keeps the Name and CodeName properties of the source worksheet.
If the copied worksheet held a worksheet code sheet in a VBA project, that is also carried into the new
workbook.
Dim ws As Worksheet: Set ws =
Dim wsBefore As Worksheet: Set wsBefore =
ws.Copy Before:=wsBefore
As an example, assuming Book1.xslx is open in Excel, the following code copies the Active sheet from the workbook containing the macro
into Book1.xlsx before Sheet1
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim wbBefore As Workbook: Set wbBefore = Application.Workbooks("Book1.xlsx")
Dim wsBefore As Worksheet: Set wsBefore = wbBefore.Sheets("Sheet1")
ws.Copy Before:=wsBefore
Dim ws As Worksheet: Set ws =
Dim wsAfter As Worksheet: Set wsBefore =
ws.Copy After:=wsAfter
Dim ws As Worksheet: Set ws =
ws.Copy
wb.Worksheets(Array("Sheet1", "Sheet2", "Sheet4")).Copy
Dim ws As Worksheet: Set ws =
ws.Delete
The problem with this code is that the process gets interupted by a confirmation prompt, which may not be what you want.
Dim ws As Worksheet: Set ws =
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
If you want to easily change the visiblity of the worksheet via the menu:
Dim ws As Worksheet: Set ws =
ws.Visible = XlSheetVisibility.xlSheetHidden
Note
If you want to allow the users to make the worksheet visible via the menu:
Dim ws As Worksheet: Set ws =
ws.Visible = XlSheetVisibility.xlSheetVeryHidden
Dim ws As Worksheet: Set ws =
ws.Visible = XlSheetVisibility.xlSheetVisible
Dim ws As Worksheet: Set ws =
Dim strPassword As String: strPassword =
ws.Protect Password:=strPassword
ws.Protect
By default, all cells are locked, but this does not take effect until you protect the worksheet. When you protect the sheet, all cells are locked
except those that you have specifically unlocked.
Dim strPassword As String: strPassword =
ws.Unprotect Password:=strPassword
If the password is omitted, you can unprotect the worksheet or workbook without specifying a password.
Warning
Dim ws As Worksheet: Set ws =
Dim strPassword As String: strPassword =
ws.Protect Password:=strPassword, DrawingObjects:=True, Contents:=True, Scenarios:=True, _
UserInterfaceOnly:=True, AllowFormattingCells:=False, AllowFormattingColumns:=False, _
AllowFormattingRows:=False, AllowInsertingColumns:=False, AllowInsertingRows:=False, _
AllowInsertingHyperlinks:=False, AllowDeletingColumns:=False, AllowDeletingRows:=False, _
AllowSorting:=False, AllowFiltering:=False, AllowUsingPivotTables:=False
Private Sub Workbook_Open()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Protect UserInterfaceOnly:=True
Next ws
End Sub
You don't need to protect the sheet with a password just to use the user interface option. If the sheet already is protected with a password
just use the userinterfaceonly line.
If ActiveSheet.Protection.AllowInsertingColumns = False Then
ActiveSheet.Protect AllowInsertingColumns:=True
End If
Dim booProtectContents As Boolean
booProtectContents = ws.ProtectContents
DrawingObjects
True to protect shapes. The default value is True.
Contents
Protects the locked cells.
Scenarios
True to protect scenarios. This argument is valid only for worksheets. The default value is True.
AllowFormattingCells
True allows the user to format any cell on a protected worksheet. The default value is False.
AllowFormattingColumns
True allows the user to format any column on a protected worksheet. The default value is False.
AllowFormattingRows
True allows the user to format any row on a protected. The default value is False.
AllowInsertingColumns
True allows the user to insert columns on the protected worksheet. The default value is False.
AllowInsertingRows
True allows the user to insert rows on the protected worksheet. The default value is False.
AllowInsertingHyperlinks
True allows the user to insert hyperlinks on the worksheet. The default value is False.
AllowDeletingColumns
True allows the user to delete columns on the protected worksheet
AllowDeletingRows
True allows the user to delete rows on the protected worksheet
AllowSorting
True allows the user to sort on the protected worksheet. Every cell in the sort range must be unlocked or unprotected. The default value is
False.
AllowFiltering
True allows the user to set filters on the protected worksheet. Users can change filter criteria but can not enable or disable an auto filter.
Users can set filters on an existing auto filter. The default value is False.
AllowUsingPivotTables
True allows the user to use pivot table reports on the protected worksheet. The default value is False.
Below shows code that implements the test IsValidSheetName. It is included in Code VBA module
modSheetProcedures.bas in folder \Documents\VBA Code\Excel\Worksheet .
Private Const ciMaxLenSheetName As Integer = 31
Private Function SheetNameIllegalCharacters() As Variant
SheetNameIllegalCharacters = Array("/", "\", "[", "]", "*", "?", ":")
End Function
Public Function IsValidSheetName(strSheetName As String) As Boolean
IsValidSheetName = False
If Len(strSheetName) = 0 Then Exit Function
If Len(strSheetName) > ciMaxLenSheetName Then Exit Function
Dim varSheetNameIllegalCharacters As Variant: varSheetNameIllegalCharacters = SheetNa
meIllegalCharacters
Dim i As Integer
For i = LBound(varSheetNameIllegalCharacters) To UBound(varSheetNameIllegalCharacters
)
If InStr(strSheetName, (varSheetNameIllegalCharacters(i))) > 0 Then Exit Function
Next i
IsValidSheetName = True
End Function
Public Function SheetExists(strSheetName As String, Optional wbWorkbook As Workbook) As B
oolean
If wbWorkbook Is Nothing Then Set wbWorkbook = ActiveWorkbook 'or ThisWorkbook -
whichever appropriate
Dim obj As Object
On Error GoTo HandleError
Set obj = wbWorkbook.Sheets(strSheetName)
SheetExists = True
Exit Function
HandleError:
SheetExists = False
End Function
UsedRange returns a Range object representing the area of a worksheet that is being used. You will use the UsedRange to work with a
range of cells in a worksheet whose size you have no control over. The UsedRange property represents the area described by the farthest
upper-left and farthest lower-right used cells in a worksheet and includes all cells in between.
As an example, with the active workheet as in the image above, running the code
?ActiveSheet.UsedRange.Address
in the Immediate window will return $B$2:$C$4. From this we can conclude that UsedRange:
is a rectangle range,
includes cells containing data or being formatted and possibly other things,
does NOT automatically include topleft cells such as A1,
does NOT consider the active cell as 'used'.
Warning
If you are only inserted in data you must be aware that not all rows actually contain data - there may be other reasons a row is included,
as in the above example includes the formatted cell C4.