Anda di halaman 1dari 5

VBA SUMMARY

1. VBA Sub and Function Procedures


Sub Procedure
- Display purposes
Sub SubProcedureName ()
Statements
End Sub

Function Procedure
- Returns a value
Function FunctionName (parameters)
Variable = Value
End Function
- Executing a function
From a Sub procedure
Sub CallerSub ()
Answer = FunctionName (ParameterValue)
MsgBox Answer
End Function
Use the function in a worksheet formula
= FunctionName (ParameterValue)

2. Essential VBA Language Elements


Comments

Some comments

Declare variable
- Dim - Dim VariableName Type

Dim MyName As String

- Public - variable available to all the procedures


- Static - retain their value even when the procedure ends
- Private - Const - constants

Operators
Add

Integer division

Multiply

Modulus

Mod

Divide

Logical Not

Not

Subtracts

Logical And

And

Power

Logical Or

Or

Concatenate

&

Logical XOR

XoR

Equivalent

Eqv

Implicit

Imp

Arrays
-

declare an array

Dim MyArray (1 To 100) As Double

Multidimensional array

Dim MyArray (1 To 3, 1 To 3 ) As Double

Assign value to array index

MyArray (i, j) = Value

Dynamic arrays have no pre-set number of elements

Dim MyArray () As Double

Change the number of elements in a dynamic array

ReDim MyArray (1 to 20)

Avoid destroying the old values

ReDim Preserve MyArray (1 to 20)

3. Range Objects
Range object
- Represents a range contained in a Worksheet object
Worksheets (SheetName).Range (A1:C5)

Value property
Assign value to cell
Worksheets (SheetName).Range (A1).Value = Value

Text property
returns a string that represents the text cells - the formatted value
Range (A1:C3).Count

Count property
returns the number of cells in a range

Font property
returns a Font object
Range (A1).Font.Bold = True

Interior property
returns an interior object
Range (A1).Interior.Color = 00000000

Formula property
represents the formula in a cell
Range (A1).Formula = =SUM (A1:A7)

NumberFormat property
represents the formula in a cell
Columns(A:A).NumberFormat = 0.00

Select method
selects a range of cells
Worksheets(SheetName).Activate
Range(A1:A2).Select

Goto method
Go to selected range/sheet
Application.Goto Reference:=Worksheets("Sheet2").Range("A1")

Copy and Paste methods


Range(A1:A12).Copy Range(C1

Clear/ClearContents/ClearFormats method
Deletes the contents of a range and cell formatting
Columns (D:D).Clear
ClearContents deletes the contents of the range but leaves the formatting intact
ClearFormats - deletes the formatting in the range but not the cell contents

4. VBA and Worksheet Functions


Total = Application.WorksheetFunction.Sum(Range(A1:A12))

VLOOKUP function
Price = WorksheetFunction.VLOOKUP(PartNum, Range(PriceList), 2,
False)

5. Loops
The If-Then structure
Sub SubProcedureName()
If Condition Then
Statements
Else
Statements
End If
End Sub

Anda mungkin juga menyukai