Objects in Microsoft Excel

advertisement
Objects in Microsoft Excel, Open Event, and Procedures
Application : The primary object in any application. Since you have entered the Visual
Basic Editor from within and Excel spreadsheet the application is Excel
Workbooks: You may have more than one Excel project open at the same time. If so
workbooks(1) refers to the first workbook.
Worksheets: There may be one or more worksheets in each workbook. Worksheet(1)
refers to the first worksheet.
Range: One or more cells may be referenced. For example:
?application.workbooks(1).worksheets(1).range(“A1”).value
would print the contents of cell A1 from the first worksheet in the first workbook
Select: Select is used to select one or more cells from the active worksheet. The
following statement will only work if the current active worksheet is the first
worksheet: application.workbooks(1).worksheets(1).range(“A1”).select
Here are some examples:
1. Print the number of worksheets in the first workbook
?application.workbooks(1).worksheets.count
2. Print the name of the second worksheet
?application.workbooks(1).worksheets(2).name
3. Select the range A1 to E10 from the first workbook, second worksheet
Application.workbooks(1) .worksheets(2).range(“A1:E10”).select
4. Print the contents of cell B12 from the first worksheet in workbook 1.
?application.workbooks(1).worksheets( 1).range(“B12”).value
5. Assign the value 123 to cells A1, C1, and E1, in worksheet one of workbook one
Application.workbooks(1).worksheets(1).range(“A1, C1, E1”).value = 123
6. Place the Sum formula into cell b12. It will sum the values from B4 to B11.
Application.workbooks(1).worksheets(1).range(“B12”).formula = “=Sum(B4:B11)”
7. Format the range A1 to D13 in Accounting2. This should be on one line. It will
stretch to the right. There is a space between autoformat and the word format.
application.Workbooks(1).Worksheets(1).range("A1:E7").autoformat
format:=xlrangeautoformataccounting2
Open Event of Workbook
The open event of a workbook can be coded by:
 Visual Basic Editor. Tools/ Macro/ Visual Basic Editor
 Left Click on the word ThisWorkbook to select it
 Right click and select View Code
 From the left drop down menu at the top of the code window select Workbook
 From the right drop down menu at the top of the code window select Open

Enter the code
Entering a Procedure (also called a macro)
 Left click on VBAProject (Book )
 From the top menu select: Insert/ Module
 From the top menu select Insert/Procedure
 Give the procedure a name. It will be Sub and Public.
 Enter the code.
Download