- Back to Home »
- VBA »
- [VBA] WorkBook_produce
Friday, November 29, 2019
Option Explicit
'Struct: workbook.worksheet.Cell/Range
'Select workbook: Workbooks("workbookName")
'NOTE:
' ThisWorkbook: this vba source code owner workbook
' ActiveWorkbook: in case mutiple workbook are opened, ActiveWorkbook which is selected(focus)
' Worksheet RUN ON ActiveWorkbook
' -> ActiveWorkbook.ActiveSheet.Cell/Range
' -> BE CAREFUL WHEN OPENED MULTIPLE WORKBOOK AT THE SAME TIME
'Select worksheet: by name Worksheets("worksheetName") or by index Worksheets(1), Worksheets(2)
'Select current worksheet: ActiveSheet
'Create new blank workbook
Sub workbook_add()
Dim NewBook As Workbook
Set NewBook = Workbooks.add
Debug.Print "NewBook name: " & NewBook.Name
End Sub
Sub Workbook_open_save()
Dim filepath As String, filename As String
filename = "mywb.xlsx"
filepath = "C:\Users\NinhLD\Downloads\vba\workbook\" & filename
'OPEN WORKBOOK
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Open(filepath)
Debug.Print "ThisWorkbook.Name: " & ThisWorkbook.Name
Debug.Print "targetWorkbook.Name: " & targetWorkbook.Name
'OPENED WORKBOOK INSTANCE
With targetWorkbook
'EDIT WORKBOOK
.Worksheets("Sheet1").Cells(1, 1).Value = "test text"
Application.DisplayAlerts = False
.SaveAs filename:=ThisWorkbook.path & "\copbook.xlsx" 'save mywb.xlsx as other copbook.xlsx
.Close SaveChanges:=True 'and CLOSE(SAVE change) mywb.xlsx
Application.DisplayAlerts = True
End With
'NOTE close without saving
'Workbooks("BOOK1.XLS").Close SaveChanges:=False
End Sub
Sub workbook_active()
Workbooks("book.xlsx").Activate
ThisWorkbook.Activate
End Sub
Sub workbook_listall()
Debug.Print "Number of opened workbook: " & Workbooks.Count
Dim Item As Workbook
For Each Item In Workbooks
Debug.Print "Workbook item: " & Item.Name
Next
End Sub