0% found this document useful (0 votes)
7 views

Chapter 1: Introduction To VBA: Common Uses of VBA

Computer tips are the best for submission

Uploaded by

suyashkaranje74
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter 1: Introduction To VBA: Common Uses of VBA

Computer tips are the best for submission

Uploaded by

suyashkaranje74
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Chapter 1: Introduction to VBA

VBA is the acronym for Visual Basic for Applications. It is an


integration of Microsoft’s event driven programming languages visual basic
with Microsoft office applications. This is the standard macro language used
in most Microsoft office products like excel, access etc. there is built in visual
basic editor in Microsoft excel that can be used to customize and extend
capabilities of ms excel. The applications built with ms excel are called visual
basic for applications or simply VBA.
Common uses of VBA
 Customizing and extending the functionality of the application in which
it is used.
 Automating a task you perform frequently Ex. Monthly reports etc.
 Automating repetitive operations Ex. Repeating a set of actions on
many workbooks.
 Creating a custom command for ex. One that combines many
commands to make the work faster.
 Creating user interactive forms and controls like buttons to which
macros or code can be assigned.
 Developing new worksheet functions that can greatly simplify your
formulas.
 Creating complete, macro-driven applications.
Some of the common applications of VBA are:
 Keeping lists of things such as employee’s details, customer’s records,
students grades etc.
 Customized data entry with subsequent actions included
 Budgeting and forecasting
 Data analysis
 Developing charts from data
Common terms used in Excel VBA
1. Object oriented programming
The word object is used to describe just about everything in Excel. In Excel, an
object can be form, button, chart or even the Visual basic editor itself.
In object oriented programming a class is a code element that defines an object. A
good analogy for a class module is the specification that defines a window, button
or a sheet etc. you create an object using the class as its specification. The object
hierarchy is as follows:
 Application
 Workbook
 Worksheet
 Range
When you have a group of objects that are related, this is then known as a
“Collection”.
2. Properties
Properties are attributes of an object. They are used to define an object
characteristic. For example: the worksheet objects has many properties, one of
which would be its name, by changing the visible property, we may hide or unhide
it. Examples of properties are height, width, font color, name etc.
3. Macros
A macro is a set of commands bundled together under one name. These
logically pre-recorded commands can be re executed at any stage to repeat
the task they were designed for. Macros simplify the work by eliminating
rewriting the code or repeating the same steps in case of frequently needed
actions.
4. Procedures
Procedures are a named set of statements that are executed as a whole. They
tell excel how to perform a specific task. The two main types of procedures
are sub and function. In VBA a sub procedure either results from recording
a macro or results in the creation of a macro, while Function procedure
must be written only manually. All subs must end with end sub.
5. Methods
A method is simply a procedure that acts on an object. It makes the object do
something, like opening a workbook or deleting a worksheet etc. for example
copy, delete, save methods of the worksheet, the add item and clear methods
of the combo box and list box etc.
6. Events
An event in excel VBA is the reason or trigger for an action to take place. For
example a mouse click is an event, double clicking an object is an event,
closing or opening of a workbook are also events.
7. Modules
Modules are containers for holding VBA code. Modules can contain
declaration and procedures. VBA code that is placed in one or more modules
can be called from an office application to perform a specified task.
There are two types of modules: standard modules and class modules.
Standard modules are modules that contain procedure that are not associated
with any particular object. Class modules are modules that are associated
with a particular object. Class modules can be used either for form or report
modules or for custom objects accessible throughout your VBA application.
The visual basic editor
The visual basic editor is where the actual programming is done. There are
many ways to access the VBA editor. One among them is using the shortcut
key Alt+F11. You can also access the visual basic editor from View->
Macro ->Edit from the Excel Worksheet.

Tool bar Menu


bar

Project window

Properties
window

Immediat
e window
Chapter 2: Data types in VBA
Variables: Variables are entities that hold data. In VBA, variables are areas
allocated by the computer memory to hold data.
The following are the variables naming rules in VBA:
1) A variable name must start with a letter and not a number. Numbers
can be included within the name, but not as the first character.
2) A variable name can be no longer than 250 characters.
3) A variable name cannot be the same as keywords.
4) No blank space allowed. You can separate words by using the
underscore( _ ) for eg. Roll_no

Declaring variable:
To declare a variable we use the word “Dim” (short for dimension) followed
by our chosen variable name then the word “as” followed by the variable
type. For ex. Dim n As integer.
You may also combine more variables to be declared in one line, separating
each variable with a comma, as follows: Dim first_name As String,
joining_date As Date, pay As Integer

Keywords: Keywords in Excel VBA are words that Excel has set aside to
use in the execution of code. This means we cannot use them for any other
purpose. For example: select, active, sub, end, function etc. are all keywords.
Some of the reserved keywords as shown in table 1.

ByVal Call Case CBool Cbyte CDate


CDbl Cint CLng Const CSng CStr
Date Dim Do Double Each Else
ElseIf End EndIf Error False For
Function Get GoTo If Integer Let
Lib Long Loop Me Mid Mod
New Next Not Nothing Option Resume
Or(Condition Private Public ReDim REM String
)
Select Set Single Static Step vbCrLf
Sub Then To True Until vbTab
With While Xor
Data Types:
Data types are classifies into two major categories.
Numeric and non numeric data types.
Numeric data types as shown in table 2.

Data Type Storage Range of values


Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
Single 4 bytes -3.402823E+ to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values
Double 8 bytes -1.79769313486232e+308 to -
4.94065645841247E-324 for negative values
4.94065645841247E-324 to
1.79769313486232e+308 for positive values
Currency 8 bytes -922,337,203,685,477.5808 to
922,337,203,685,477.5807
decimal 12 bytes +/- 79,22,162,514,264,337,593,543,950,335 of no
decimal is use
+/-7.9228162514264337593543950335(28 decimal
places)

Non numeric data types as shown in table 3.

Data Type Storage Range of values


String (fixed Length of string 1 to 65,400 characters
length)
String(variable Length +10 bytes 0 to 2 billion characters
length)
Date 8 bytes January 1,100 to
December 31,9999
Boolean 2 bytes True or false
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as
double
Variant(text) Length +22 bytes Same as variable
length string
Chapter 3: Message Box and Input Box in VBA
In VBA Message Boxes fall into two basic categories, the MsgBox method
and the MSgBox function.

The MsgBox method


The msgbox method is used to display a pre-defined message to the user. It
also contains a single command button “OK” to allow the user to dismiss the
message and they must do so before they can continue working in the
program.
The basic form of the message box(msgbox) in VBA is: MsgBox(“message”)

Example:
Sub result( )
MsgBox ("Congradulations")
End Sub
This displays the message box as shown in fig.

Customize the buttons in a VBA message box


The msgbox can be customized by changing the buttons and icons placed on
it.
For example:
Sub result()
Dim n As Integer
n = MsgBox("Congradulations", vbExclamation, "result")
End Sub

This will produce the following result as shown in fig.


A list of various buttons and icons that can be used in the VBA message box
is shown in the table.

Constant Description
vbOKOnly It displays a single OK button
vbOKCancel It displays two buttons OK and Cancel
vbYesNoCancel It displays three buttons Yes, No and Cancel.
vbYesNo It displays two buttons Yes and No.
vbQuestion It displays a query icon.
vbExclamation It displays a warning message icon.
vbDefaultButton1 First button is treated as default.
vbDefaultButton2 Second button is treated as default.
vbDefaultButton3 Third button is treated as default.
vbMsgBoxHelpButton This adds a Help button to the message box.

The MsgBox Function


The msgbox function displays a message in a dialog box, waits for the user to
click a button, and then returns an integer indicating which button was
clicked by the user. The syntax of the Msgbox( ) function is:
Return value=MsgBox(Prompt, button and Icon types, title, Help file,
help file context)
Where,
Return value: Indicates the action the user took when the message box was
shown to him/her.
Prompt: It is the message contained in the main body of the message box.
Button and Icon types: this specifies the set of buttons and icons and their
placement as they would appear to the user.
Help file: This is the path to a help file that the user can refer to on this topic.
Help file context: This is the pointer to that part of the help file that
specifically deals with this message.
Sub test( )
Dim a As Integer
a = MsgBox("Do you want to print this file?", vbYesNo,
"Action on Files")
End Sub
This will produce the result as in fig.

VBA msgbox function returns a value based on the user input. These values
can be anyone of the ones as shown in table.
Value Description
1 Specifies that OK button is clicked.
2 Specifies that Cancel button is clicked.
3 Specifies that Abort button is clicked.
4 Specifies that Retry button is clicked.
5 Specifies that Ignore button is clicked.
6 Specifies that Yes button is clicked.
7 Specifies that No button is clicked.

Reading the msgbox( ) return values


Based on the value returned by the msgbox( ), decisions can be made.
For eg: The code mentioned here will display the message box and when the
user clicks “Yes” it will display a congratulatory message. If the user clicks
“No” another message “Better luck next time” will appear.

Sub result( )
Dim n As Integer
n = MsgBox("Did you score more then 50%", vbYesNo,
"Printing file")
If n = 6 Then
MsgBox ("Congratulations")
Else
MsgBox ("Better luck next time")
End If
End Sub

Input box
For accepting the input from the user the input box is used in two ways- the
input box method and the input box function.
The input box method
The input box method differs from the input box function in that it allows
selective validation of the user’s input, and it can be used with Microsoft
excel objects, error values and formulas.
Its syntax is:
Inputbox (prompt,title,default,left,top,helpfile,helpcontextid,type)
Type that allows specifying the type of data we are going to collect. These
are as shown below:
Type:=0 A formula
Type:=1 A number
Type:=2 Text(a string)
Type:=4 A logical values(true or False)
Type:=8 A cell reference, as a Range object
Type:=16 An error value, such as #N/A
Type:=64 An array of values
For eg:
Sub test( )
Dim n As Integer
n = Application.InputBox("Enter your age:", "Personal
details", , , , , , 1)
If (n > 60) Then
MsgBox "you are eligible for senior citizen's concession"
Else
MsgBox "no concession"
End If
End Sub

The input box function


The input box function displays a dialog box for user input. It returns the
information entered in the dialog box. The syntax for the input box function
is:
Inputbox(prompt,title,default,xpos,ypos,helpfile,context)
Chapter 4: Decision making in VBA
Introduction:
In a program a set of statements are normally executed sequentially in the
order in which they appear. This happens when no decision making or
repetitions are involved. But in reality, there may be a number of situations
where we may have to change the order of execution of statements based on
certain conditions being true or false.
Some of the examples may be:
a. To decide if a trainee is to be declared “Passed” or “Failed”
b. To display the Grade achieved by a student.
c. To decide if a number is prime or not.
d. To decide if a string is a palindrome or not.
e. To calculate pay, tax, commission etc. based on certain conditions etc.

The If….then statement


It is the simplest form of control statement, frequently ued in decision making
and changing the control flow of the program execution.
Syntax:
If (condition) then
‘code if the condition is met
End If
Eg:
If(age<18) then
Debug.print “Not eligible”
End If

The If Then … Else Statement


When an action has to be taken if the condition returns true and another
action if the condition returns false, then we use the if then …. Else
statement.

Syntax:
If condition then
‘ code if the condition is met
Else
‘code if the condition is not met
End if
Eg:
Sub test( )
Dim income as long
Income=application.inputbox(“Enter you Taxxable income”)
If income<25000 then
Msgbox ”you need not pay any income tax”
Else
Msgbox ” you must pay income tax”
End if
End sub
Using multiple if statements
Sometimes the condition being tested is to be evaluated not just for returning
“True” or “False” based on one condition, but for multiple conditions too. In
such cases the multiple if then …. Else statements can be used.

Else if ladder statement


Syntax:
If (condition) then
{
‘ code if the condition is true
}
Else if(condition) then
{
‘ code if the condition is true
}
Else if(condition) then
{
‘ code if the condition is true
}
Else
{
‘ code if the condition is true
}
Eg:
Sub grade( )
Dim marks As Integer
marks = InputBox(“Enter marks:”)
If marks >= 80 Then
MsgBox “Distinction”
ElseIf marks >= 70 Then
MsgBox “A Grade”
ElseIf marks >= 60 Then
MsgBox “B Grade”
ElseIf marks >= 40 Then
MsgBox “C Grade”
Else
MsgBox “Failed”
End If
End Sub
Nested if Statements
Syntax: If (condition 1)
{
‘ code if the condition 1 is true
If(condition 2)
{
‘ code if the condition 2 is true
}
Else
{
‘ code if the condition 2 is false
}
Else
{
‘ code if the condition 1 is false
}
Eg:
Sub job_test( )
Dim experience, marks As Integer
experience = InputBox("Enter your work experience in years")
If experience >= 5 Then
marks = InputBox("Enter your marks percentage")
If (marks >= 75) Then
MsgBox ("You are eligible for the post")
Else
MsgBox ("You are NOT eligible for the post")
End If
Else
MsgBox ("You are NOT eligible for the post")
End If
End Sub

Select …Case
Select…case statements can be used to easily evaluate the same variable
multiple times and then take a particular action depending on the evaluation.
Syntax:
Select case variable
Case value1
‘code to run if variable equals value1
Case value2
‘code to run if variable equals value2
Case value3
‘code to run if variable equals value3
Case else
‘code to run for remaining cases
End select
Eg:
Sub players()
Dim game As String
game = InputBox("Enter the name of the game")
Select Case game
Case "tennis"
Debug.Print "2 players"
Case "cricket"
Debug.Print "11 players"
Case "baseball"
Debug.Print "9 players"
Case Else
Debug.Print "I have no idea."
End Select
End Sub

Chapter 5: Loops in VBA


Introduction
There may be many situations where you need to perform a task repeatedly/ a
certain number of times. In such cases the code for the task is placed inside a
loop and the program iterates or repeats through the loop a certain number of
times i.e. Till a certain condition is met.
VBA provides the following types of loops to handle looping requirements.
Loop Type Description
For….next loop Execute a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
Do…until loop Repeats a statement or group of statement until a
condition is met.
Do…while loop Repeats a statement or group of statement as long as
the condition is true.

The for loop


The for…next loop sets a variable to a specified set of values and for each
value runs the VBA code inside the loop. For ex.
For n=1 to 10
debug.print n
next n

The for each loop


The for each loops through every object within a set of objects. The
following example would print the names of all the worksheets.
Sub forloop( )
Dim ws As Worksheet
For Each ws In Worksheets
Debug.Print ws.Name
Next ws
End Sub

The exit for statement


If you need to end the For loop before the end condition is reached. Exit for
always comes with if condition.
Sub forloop( )
For n = 0 To 10 Step 1
Debug.Print n
If n = 6 Then Exit For
Next n
End Sub

The do…until loop


The do…until loop repeats a statement or group of statement until a condition
is met.
There are 2 ways a do until loop can be used.
Eg:
Do until ….loop
Sub doloop()
Dim n As Integer
n=5
Do Until (n = 10)
Debug.Print n
n=n+1
Loop
End Sub
Do …loop until
Sub doloop( )
Dim n As Integer
n=1
Do
Debug.Print n
n=n+1
Loop Until n = 10
End Sub

The do while…loop
The do while…loop repeats a statement or group of statements as long as the
condition is true.
Like the do until loop, a do while loop can be also be used in two ways.
Eg:
Sub dowhileloop( )
Dim n As Integer
n=1
n < 10
n=n+1
Debug.Print n
Loop
End Sub
Do…loop while
In a do…loop while, a set of statements in the loop are executed once, then
the condition is checked. The code in the loop is executed only if the
condition is met.
Eg:
Sub doloopwhile()
Dim row As Integer
row = 0
Do
row = row + 1
Debug.Print row
Loop While row < 10
End Sub

Chapter 6: String manipulation in VBA


Introduction
A string is a type of data variable which can consist of text, numerical values,
date and time and alphanumeric characters.
String concatenation
String concatenation or joining two or more strings can be done by the “+”
operator.
Eg:
Sub strcat( )
Dim a, b, c As String
a = "www"
b = "and"
c = "the Internet"
Debug.Print a + b + c
End Sub

Len( )function
Returns an integer containing either the number of characters in a string.
Syntax: len(string)
Eg:
Sub strcat()
Dim a As String
a = "Computer Operator and Programming Assistant"
Debug.Print "the length of the string is " & Len(a)
End Sub
Left( )
Returns a string containing a specified number of characters from the left side
of a string.
Syntax: left( string,Int)

Right( )
Returns a string containing a specified number of characters from the right
side of a string.
Syntax: right(string,Int)

Mid( )
Returns a string that contains all the characters starting from a specified
position in a string
Syntax: mid(string,int) or mid(string,int,int)
Examples:
1) Sub stringpro( )
Dim a As String
s = "Indian Army"
Debug.Print Left(s, 5)
End Sub
2) Sub stringpro( )
Dim a As String
s = "Computer"
Debug.Print Right(s, 5)
End Sub
3) Sub stringpro( )
Dim s As String
s = "wholehearted"
Debug.Print Mid(s, 6)
End Sub
4) Sub stringpro( )
Dim s As String
s = "wholehearted"
Debug.Print Mid(s, 6, 4)
End Sub
Ltrim( )
Returns a string containing a copy of a specified string with no leading spaces
Syntax: Ltrim(string)
Rtrim( )
Returns as string containing a copy of a specified string with no trailing
spaces.
Syntax: Rtrim(String)
Trim( )
Returns a string containing a copy of a specified string with no leading or
trailing spaces.
Syntax: Trim(String)
Example:
Sub stringpro()
Dim s As String
s = " Adjustment "
Debug.Print "For everyone" & LTrim(s) & "is a must"
Debug.Print "For everyone" & RTrim(s) & "is a must"
Debug.Print "For everyone" & Trim(s) & "is a must"
End Sub

Instr( )
Returns an integer specifying the start position of the first occurrence of one
string within another.
Syntax: instr([start,]string1,string2[,compare])
Eg:
Sub stringpro()
Dim a, b As String
a = "hairdresser"
b = "dress"
Debug.Print "The second string starts at position no.:" & InStr(1, a, b)
End Sub
Replace( )
The replace( ) function replaces a sequence of characters in a string with
another set of characters.

Eg:
Sub stringpro()
Debug.Print Replace("majority", "aj", "in", 1)
Debug.Print Replace("think and think", "i", "a", 1, 1)
End Sub
Val( )
The val( ) function accepts a string as input and returns the numbers found in
that string.
Syntax: val(string)
Eg:
Sub stringpro()
Dim s1, s2, s3 As String
s1 = "6 feet 1 inch is his height"
s2 = "5-6 kms is the distance to my office from here."
s3 = "0112222222 is my phone number"
Debug.Print Val(s1)
Debug.Print Val(s2)
Debug.Print Val(s3)
End Sub
The string conversion function
 Lcase( )
Returns a string or character converted to Lowercase.
Syntax: Lcase(string)
 Ucase( )
Returns a string or character converted to Uppercase.
Syntax: Ucase(string)
Eg:
Sub stringpro()
Dim a, b As String
a = "IF YOU FEAR YOU WILL BECOME WEAK"
b = "be a strong person"
Debug.Print LCase(a)
Debug.Print UCase(b)
End Sub

 Asc( )
The Asc( ) function returns an integer value representing the ASCII code
corresponding to a character or the first character in a string.
Syntax: Asc(string)
Eg: Asc(“A”) will return 65

 Chr( )
The chr( ) function returns the character associated with the specified ASCII
code.
Syntax:Chr(Integer)
Eg: Chr(68) will return the character “D”

Reverse String
 StrReverse
Returns a string in which the character order of a specified string is reversed.
Syntax: StrReverse(string)
Eg:
Sub stringpro( )
Dim a As String
a = "desserts"
Debug.Print StrReverse(a)
End Sub

Chapter 7: Built-in functions in VBA

Introduction
VBA has a rich collection of built in functions that perform a variety of tasks
and calculations. Using the VBA built in functions will help coding much
easier for the user.

Math functions

Function name Description


Abs Returns the absolute value of a number.
Cos Returns the cosine of the specified angle.
Cos Returns the hyperbolic cosine of the specified angle.
Exp Returns the raised to the specified power.
Fix Returns the integer portion of a number.
Takes a numeric expression and returns it as a
Format
formatted string.
Int Returns the integer portion of a number.
Returns the natural (base e) logarithm of a specified
Log
number.
Rnd Generates a random number(integer value)
Returns a decimal or double value rounded to the
Round
nearest integral value
Returns an integer value indicating the sign of a
Sign
number.
Sin Returns the sine of the specified angle.
Sqr Returns the square root of a specified number.
Tan Returns the tangent of the specified angle.
Accepts a string as input and returns the numbers
Val
found in that string.

Eg:
Dim a as integer
a=81
Debug.print sqr(a)
This will display the square root of 81 i.e.9
Logical functions

Function name Description


Isdate Returns TRUE if the expression is a valid date.
Otherwise, it returns FALSE
Iserror Checks for error values.
Returns TRUE if the expression is a null value.
Isnull
Otherwise, it returns FALSE
Returns TRUE if the expression is a valid number.
Isnumeric
Otherwise, it returns FALSE
Eg:
Sub abc( )
Dim n As Variant
n = InputBox("enter number")
If IsNumeric(n) = True Then
MsgBox "correct"
Else
MsgBox "Insert only numbers"
End If
End Sub
Date / Time functions
Function name Description
DATE Returns the current system date.
DATEDIFF Returns the difference between two date values.
DATESERIAL Returns a date given a year, month and day value.
DAY Returns the day (a number from 1 to 31) of the given
date value.
HOUR Returns the hour of a time value(0 to 23)
MINUTE Returns the minute of a time value(0 to 59)
MONTH Returns the month ( from 1 to 12) given a date value.
MONTHNAME Returns a string representing the month given a
number from 1 to 12
NOW Returns the current system date and time.
YEAR Returns the year portion of the date argument.
WEEKDAY Returns a number representing the day of the week,
given a date value
List of valid interval values
Interval Explanation
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
h Hour
n Minute
s Second

Eg:
Sub test()
Debug.Print DateDiff("yyyy", "1/12/1999", "31/1/2003")
End Sub
The result will be
4

Data type conversion functions


Function Return Type Range for expression argument
CByte Byte 0 to 155
CBool Boolean Any valid string or numeric expression
CDate Date Any valid date expression
CInt Integer -32,768 to 32,767
CStr String Returns for CStr depend on the expression
argument.
Eg:
Sub test()
Dim a As String
a = 12345
Debug.Print CDate(a)
b = "january 1,1990"
Debug.Print CDate(b)
c = "1:23:45 PM"
Debug.Print CDate(c)
End Sub
This will display
10/18/1933
1/1/1990
1:23:45 PM

Chapter 8: Arrays
Introduction
An array is a group of variables of the same data type and with the same
name.
Declaring an array
Dim students(10) as integer
Dim sname(3) as string
Eg:
Sub array_test()
Dim arr(5) As Integer
Dim n As Integer
arr(0) = 89
arr(1) = 83
arr(2) = 62
arr(3) = 99
arr(4) = 56
For n = 0 To 4
Debug.Print arr(n)
Next
End Sub
Types of arrays:
1. Static arrays
2. Dynamic arrays
Static array: A static array is an array that is sized in the Dim statement that
declares the array.
Eg:Dim staticarray(1 to 10) as long
You cannot change the size or data type of a static array.

Dynamic Array: A dynamic array is an array that is not sized in the dim
statement. Dynamic array variables are useful when we don’t know in
advance how many elements need to be stored in the array.
Eg: Dim DynamicArray( ) as long

Chapter 9: Form in VBA

Introduction Forms and Controls


A form is a document designed with a standard structure and format
that makes it enter, organize, and edit information. Forms contain labels,
textboxes, drop down boxes and command buttons too.
By using forms and the many controls and objects that you can add to
them. You can significantly enhance data entry on your worksheets and
improve the way your worksheets are displayed.

Types of Excel forms


There are several types of forms that you can create in Excel. Worksheets hat
contains form and Activex controls and VBA user forms.

Worksheet with Form and Activex controls


A worksheet can be considered to be a form that enables to enter and view
data on the grid.
For added flexibility you can add controls and other drawing objects to the
worksheet and combine and coordinate them with worksheet cells. For
example you can use a list box control to make it easier for a user to select
from a list of items.

Creating VBA forms


A VBA form can be created from the code window. To create a Form in
VBA, click on Insert menu in the code window and then click “user form”. A
userform1 appears in the project window.
Some of the events and methods connected with the form object are:
Events Methods
Activate Copy
Deactivate Paste
Add control Hide
Remove control Move
Click Print Form
Dblclick Show
Keypress
Resize
Scroll
Terminate

The code needed to perform various operations on forms is given in table.


User form VBA code Action
application
To display a userForm1.show Displays the UserForm with name
UserForm UserForm1
Remove a Unload UserForm1 To unload the UserForm from
user for memory
/close
UserForm
Hide a UserForm1.Hide Using the hide methods will
UserForm temporarily hide the UserForm, but
will not close it.
Print a UserForm1.PrintForm The UserForm dirlectly sends for
UserForm printing.
Set Userform1.height=250 Set height and width of the UserForm
UserForm Userform1.width=350 in points
size
Left and top Userform1.left=30 Distance set is between the form and
properties Userform1.top=50 the left or top edge of the window that
contains it , in pixels.
Move Userform1,move Move methods include two arguments
method 200,50 which are required.

Chapter 10: Form Controls in VBA


Introduction
Controls are objects that display data or make it easier for users to enter
or edit data, perform an action or make a selection. Controls make the form
easier to use. Examples of common controls include list boxes, option buttons
and command buttons.
The summary of form controls is given in table.
Button name Example Description
Label Identifies the purpose of a cell
or text box, or displays
descriptive text such as titles,
captions.
Command Button Runs a macro that performs
an action when a user clicks
it.
Check Box Turns on or off a value that
indicates an opposite choice.
You can select more than one
check box.
Option Button Allows a single choice within
a limited set of choices.
List Box Displays a list of one or more
items of text from which a
user can choose.
Combo Box Create a drop down list.

Scroll bar Scrolls through a range of


values when you click the
scroll arrows or drag the scroll
box.
Spin Button Increases and decreases a
value. To increase the value
click the up arrow, to decrease
the value click the down
arrow.

You might also like