Sei sulla pagina 1di 32

VBA for Excel

Visual Basic for


Application
ME 325
Spring, 2007
Overview
• Controls

• Data Types

• Loops and Branching

• Sheets and Cell Reference


Online Reference
• http://msdn.microsoft.com/library/default.

• http://www.techonthenet.com/excel/

• http://www.functionx.com/vbaexcel/Les
son01.htm
Visual Basic for Applications
• VBA is a version of Visual Basic (VB)
available in most Microsoft (MS) Office
applications

• VBA is used to develop procedures,


known as Macros, that can be run
within the application itself.

• VBA have the necessary elements to


programmatically automate your
Macros
• Excel has a build-in macro recorder that
translates your actions into VBA macro
commands. 
• After you recorded the macro, you will be
able to see the layout and syntax. 
• Before you record or write a macro, plan the
steps and commands you want the macro to
perform. 
• Every actions that you take during the
recording of the macro will be recorded -
including the correction that you made.
• You can use the generated VBA code in your
custom functions.
VBA Editor
• To write code, you must open Microsoft
Visual Basic. On the main menu, click Tools
-> Macro-> Visual Basic Editor. This would
open the Microsoft Visual Basic programming
environment
Windows Controls
• The main objects used to help a person
interact with the computer are
Windows controls.
• Besides columns, rows, and cells, you
can add or position some Windows
controls on the worksheet
• To do that, on the main menu of MS
Excel, you can click View -> Toolbars
-> Control Toolbox.
Adding Window Control
• Select The control you want to add
• Click the position you want to place on
the sheet
• Click and extend the rectangle that
would host the control
The Names of Controls
Label CommandButton
TextBox TabStrip
ComboBox MultiPage
ListBox ScrollBar
CheckBox SpinButton
OptionButton Image
ToggleButton Frame
Class/Object
• The language of Microsoft Visual Basic uses
the concept of Class/Objects.
• a class is a construct that is used to group
related instance variables and methods.
• Controls are instance of a class that has
properties, attributes and events. Events are
the mean your program get notified of user
interactions with the control.
• Example of a command button properties:
text color, back color, position, …
• Button events: SingleClick, DoubleClick,
Focus, …
• Properties, Methods and Events are specific
to the Class/Object.
Control Properties
• To change the
characteristics of a
control, right click and
select properties, This
would open the Properties
window and display the
characteristics of the
selected control

• The Properties window


allows you view or change
a characteristic of the
Control Events
• Events is the way a control notify your
program of user or other interactions.
• To capture an event, right click on control
and click view code.
• You will be placed in the VB editor with a
subroutine for the
controlname_Event(arg1,arg2,…)
• To add other event click on the top right
combobox of the available events, and select
it
Parts of a Message
Private Sub WHO_WHAT(Arg1,Arg2,…)
• WHO sent the message: The name of
the Control
• WHAT message: Message Type,
Clik,Focucs,…
• Arguments: Additional information
needed to process a message if
applicable
Common Events of Windows
Controls
• Click
– Private Sub cmdSend_Click()
• Double-Click
– Private Sub cmdSend_DblClick(ByVal Cancel As
MSForms.ReturnBoolean)
• Getting Focus
– Private Sub txtFullName_Enter()
• Losing Focus
– Private Sub cboGrades_Exit(ByVal Cancel As
MSForms.ReturnBoolean)
• Keyboard Events: KeyDown, KeyUp, KeyPress
– Private Sub txtFullName_KeyDown(ByVal KeyCode As
MSForms.ReturnInteger, ByVal Shift As Integer)
• Mouse Events: MouseDown, MouseUP, MouseMove
– Private Sub cmdSend_MouseDown(ByVal Button As Integer,
ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
Variables and Data Types
• When writing your code, you can use any
variable just by specifying its name. When
you provide this name, the computer directly
creates an area in memory for it.
• To eliminate the possibility of confusion, you
can first let Visual Basic know that you will be
using a variable and reserve storage for it,
this is called variable Declaration.
• Option Explicit at the begining instruct the
compiler to catch all variables that are not
declared
• Dim variable_name as type
– Dim x as Integer
– Dim str as String
Option Explicit
• Option Explicit tells
Visual Basic that a
variable cannot be
used if it has not been
primarily declared. To
communicate this, on
top of each file you use
in the type:
Option Explicit
• click Tools ->
Options... put a check
mark in the Require
Data Types
Type Description Range

Boolean 2-bytes True or False

Byte 1-byte natural number 0 to 255

Integer 2-bytes integer – 32,768 to 32,767

Long 4-bytes Integer -2,147,483,648 to 2,147,483,647

Single 4-bytes decimal number – 3.402823E38 to 3.402823E38

Double 8-bytes decimal number – 1.79769313486231E308 to


1.79769313486231E308
Currency 8-byte number with fixed – 922,337,203,685,477.5808 to
decimal point 922,337,203,685,477.5807
String String of characters Zero to approximately two billion
characters
Date 8-bytes date/time value January 1, 100 to December 31,
9999
Data Type Conversions
• CStr(…): Convert to String
• CByte(…): Convert to Byte
• CInt(…): Convert to Integer
• CLng(…): Convert to Long
• CDbl(…): Convert to Double
• CCur(…): Convert to Currency
• CDate(…): Convert to Date
•…
VBA Loops
• A loop is an expression used to repeat
an action. Microsoft Visual Basic
presents many variations of the loops
and they combine the Do and the Loop
keywords.

• Loops can be constructed many


different ways to suit different
circumstances. Often the same result
can be obtained in different ways to
suit your personal preferences. These
exercises demonstrate a selection of
Do While … Loop
Do While Condition    
Statement(s)
Loop

This expression examines the Condition. If


the condition is true, then it executes the
Statement or statements. After executing
the statement(s), it goes back to examine
the Condition. AS LONG AS the Condition is
true, the Statement will be executed and
the Condition will be tested again.
Do...Loop While
Do
Statement(s)
Loop While Condition

In this case, the Statement or


Statements will be executed first. Then
the Condition will be tested.
The Do Until ... Loop
Do Until Condition
    Statement(s)
Loop

• This loop will first examine the


Condition, instead of examining
whether the Condition is true, it will
test whether the Condition is false.
For...To...Next Loop
For Counter = Start To End
  Statement(s)
Next

• The expression begins counting at the Start


point. Then it examines whether the current
value is smaller than End. If so, it then
executes the Statement(s). Next, it
increments the value of Counter by 1 and
examines the condition again. This process
goes on until the value of Counter becomes
equal to the End value. Once this condition is
reached, the looping stops. 
Stepping the Counting Loop
For Counter = Start To End Step
Increment
  Statement(s)
Next Counter

Same as the For loop, the next counter is


incremented/decremented by the
Increment value
Do … Loop Until, Example
Sub FillData(startRow,nRows)
Dim x as Double
Dim y as Double
Dim row as Integer

row=startRow

Do
x=Cells(row,”A”).Value
y=Exp(x)*Sin(2*x)-3.25
Cells(row,”B”).Value=y
row=row+1
 Loop Until row >(startRow+nRows)
For … Next Loop
Sub FillData(startRow,nRows)
Dim x as Double
Dim y as Double

For row=startRow to
(startRow+nRows)
x=Cells(row,”A”).Value
y=Exp(x)*Sin(2*x)-3.25
Cells(row,”B”).Value=y
The If...Then...ElseIf
Statement
If Condition1 is True Then
Statement1
ElseIf Condition2 is True Then
Statement2
ElseIf Conditionk is True Then
Statementk
End If
If Then …
Function MyFunction(x)
retVal=“N/A”
If x <10 Then
retVal=“Less Than 10”
ElseIf x<20
retVal=“10 to 20”
Else
retVal=“More Than 20”
End If
MyFunction=retVal
End Function
The Select Case Statement
Select Case Expression
Case Expression1
Statement1
Case Expression2
Statement2
Case Expressionk
Statementk
Case Else
Default statement
End Select

The Expression will be examined and evaluated once. Then


Microsoft Visual Basic will compare the result of this
examination with the Expression of each case. Once it finds
one that matches, it would execute the corresponding
Statement.
Worksheets
• The various worksheets of a workbook are stored in
a collection called Worksheets.

• A worksheet is an object that has properties/method


that can be changed/invoked

• A worksheet can be accessed by its index or name,


Sheets(index) or Sheets(“name”)
Dim mySheet as worksheet
Set mySheet=Sheets(1)
mySheet.Name=“MySheet”
mySheet.Calculate()

• To add a new work sheets, you need to use the add


method of Sheets collection
– Sheets.Add, this will add a sheet at the end of the existing
sheets
Columns, Rows, and Cells of a
Worksheet
• Columns and Rows are collections that
belong to the Sheet object
– Sheet1.Columns(“A”) is the column A
– Sheet1.Rows(3), is the row number 3
• Cells is a collection that belong to the
Sheet object. A cell is referenced by
row and column position
– Sheet1.Cells(1,1) is cell A1
– Sheet1.Cells(1,”A”) is cell A1
– Sheet1.Cells(1,1).Value return the value
stored in cell A1, the Value property is
Read/Write
Range and Names
• A cell or range of cells can be given a
name.
– Sheet1.Range(“A1:A5”).Name=“Range1”
• A range can be referenced by cell
range or by its given name
– Range(“Rang1”).Value=100, this would set
the values of cells A1 to A5 to 100

Potrebbero piacerti anche