Sei sulla pagina 1di 4

Introduction to

Object and Class


Visual Basic Application Training (for RF Engineer)

Marselinus Magtal
11/15/2014

A scribble of thought
On the 4 th page of the presentation about Microsoft Excel and Access environment you were introduce to
know things that in the Excel and Access environment. This things like Application, Worksheet,
Database, Cell, etc. are called Object by the VBA world. VBA world know these objects by define the
library references in the VBA library list. So there are actually two worlds. The Office world and VBA
world then linked together by a feature called Macro.
The question then, what is Class? If you want to make it simple you can call Class is the same as
Object. You will find this term if you dig deeper to the world of Object Oriented Programming.
And by learning Macro in Office system you already entered Object Oriented Programming entrance door.

Lets find out about object in Excel world using Macro


Step 1: Open your VBA application. Click [Developer][Visual Basic].

Step 2: Create new module. Right-click on the VBAProject then click [Insert][Module].

Step 3: Create a sub CreateExcelObjects.


Sub CreateExcelObjects()
End Sub

Step 4: Define all of the excel object.


Dim
Dim
Dim
Dim

XlApplication As Application
XlWorkbook As Workbook
XlWorksheet As Worksheet
XlRange As Range

Step 5: Create the objects. And the final code should be like this.
Sub CreateExcelObjects()
Dim XlApplication As Application
Dim XlWorkbook As Workbook
Dim XlWorksheet As Worksheet
Dim XlRange As Range
Set XlApplication = New Application 'this called create new object
Set XlWorkbook = XlApplication.Workbooks.Add 'add workbook
Set XlWorksheet = XlWorkbook.Worksheets.Add 'add worksheet
XlWorksheet.Name = "Worksheet Baru" 'give name to worksheet
Set XlRange = XlWorksheet.Range("A1") 'get the cell A1 address
XlRange.Value = "Assign value to Cell A1" 'set a value to cell A1
XlApplication.Visible = True 'show the application
End Sub

Step 6: Go back to Excel and run this macro. Click [Developer][Macro].

Step 7: Choose the macro you created before. Then click [Run].

Save the workbook as object_intro.xlsm.

Another implementation:
If you open Excel or Access application and then open VBA application, you already create Application
object and you can use it.

Open your Excel VBA. Create new Sub routine named it Main in ThisWorkbook object. And type code
below.
Sub Main()
Dim MyFileDialog As FileDialog
Set MyFileDialog = Application.FileDialog(msoFileDialogOpen)
MyFileDialog.Show
End Sub

In this code the FileDialog object already created by excel application you opened. Then we assign it by
reference to MyFileDialog variable that has the same object type with with the Application.FileDialog
object.
Note: You need to add the Office Object Library to your VBA project.

Potrebbero piacerti anche