1.2. Automation Objects

 < Day Day Up > 

If you are new to programming, the mention of objects might not make sense. Objects are programming items that make your life much easier. As an example, one of the main Excel objects is the Worksheet. The Worksheet object is a container for many other objects, such as cells, pivot tables, and charts. By using the Excel object model, you can perform many tasks with one line of code that would have taken hours if there were not another method available. Let's assume that you want to press a button on an Excel worksheet to print it. The following code prints the worksheet when you press the CommandButton1 button:

     Private Sub CommandButton1_Click( )     Dim xlws as Worksheet     Set xlws = ActiveSheet     xlws.PrintOut     Set xlws = nothing     End Sub 

In this very short procedure, you declare a variable that is an Excel Worksheet (if you were automating Excel from another application, you would declare this as Excel.Worksheet and declare another variable as Excel.Application, but while in Excel this step is not needed). Next, you set this variable equal to the active worksheet ActiveSheet represents the current worksheet in the active workbook. Once there is a reference to the active worksheet, you can call any of the methods that are part of the object. In this example, you call the PrintOut method of the worksheet. There are several objects in Excel that have a PrintOut method; in each case, it simply prints the object. The final step sets the xlws variable to nothing, which tells Excel to no longer store a reference to the object. The xlws variable in this procedure still exists, even though you are no longer using it if you were in a procedure that used several worksheets, you could set xlws to nothing and reuse that variable with any other worksheet.

This code may still look complicated, but if you did any programming in MS-DOS where you had to understand how each printer worked and how to send commands to it, you would see how simple this is by comparison.


In future chapters, you will see how to set a reference to each application and how the object model of each can be used to accomplish even the most demanding tasks. You can also get context-sensitive help while working with the VBA project, and when you are not sure how to tackle an Excel task with VBA but know how to do it with the user interface, you can always record a macro and then review the code. Please see Appendix A for a review of the most commonly used objects and their usage in Excel and Access.

     < Day Day Up > 


    Integrating Excel and Access
    Integrating Excel and Access
    ISBN: 0596009739
    EAN: 2147483647
    Year: 2005
    Pages: 132

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net