- Back to Home »
- VBA »
- [VBA] WorkSheet_produce
Friday, November 29, 2019
1. Add new sheet
Dim ws As Worksheet
Set ws = Sheets.add
ws.Name = "NewSheet1"
'or
Sheets.add
ActiveSheet.Name = "NewSheet2"
'or
Sheets.add.Name = "NewSheet3"
'or add to 1st
Sheets.add(Before:=Sheets(1)).Name = "FirstSheet"
'or add to last
Sheets.add(After:=Sheets(Sheets.Count)).Name = "LastSheet"
'or add to after
Sheets.add(After:=Sheets("Sheet1")).Name = "NewSheet4"
'or add to before
Sheets.add(Before:=Sheets("Sheet1")).Name = "NewSheet5"
2. Delete sheet
Application.DisplayAlerts = False
Worksheets("Sheet3").Delete
Application.DisplayAlerts = True
3. Move sheet
Worksheets("Sheet3").Move after:=Worksheets("Sheet1")
Worksheets("Sheet3").Move before:=Worksheets("Sheet1")
4. Copy sheet
Option Explicit
'Struct: workbook.worksheet.Cell/Range
'Select worksheet: by name Worksheets("worksheetName") or by index Worksheets(1), Worksheets(2)
'Select current worksheet: ActiveSheet
'Select or active sheet
Sub worksheet_produce()
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
'---Select sheet---
With Worksheets("Sheet1")
'EDIT worksheet "Sheet1"
.Cells(1, 1).Value = "here is sheet 1"
End With
With ActiveSheet
'EDIT current sheet
.Cells(1, 1).Value = "here is current sheet"
End With
'---Active sheet---
Worksheets("Sheet2").Activate
End Sub
Sub worksheet_listAll()
'---list all sheet---
Dim i As Integer
For i = 1 To ThisWorkbook.Sheets.Count
Debug.Print "By index: " & ThisWorkbook.Sheets(i).Name
Next i
Dim Item As Worksheet
For Each Item In ThisWorkbook.Worksheets
Debug.Print "by worksheet item: " & Item.Name
Next
End Sub
Sub worksheet_Copy()
'copy to new workbook
Debug.Print ActiveWorkbook.Name 'output: vba.xlsx
Worksheets(Array("Sheet1", "Sheet2")).Copy
Debug.Print ActiveWorkbook.Name 'output: Book1
Worksheets("Sheet1").Copy After:=Worksheets("Sheet2") 'copy Sheet1 to after Sheet2 in Book1
'NOTE: After copy ActiveWorkbook change to new Book1
End Sub