Académique Documents
Professionnel Documents
Culture Documents
Excel VBA means Excel Visual Basic for Applications which can
be created using the built-in Visual Basic Editor in Microsoft Excel. There are two ways which you can
create an Excel VBA. The first is to place a command button on the MS Excel spreadsheet and click on
the button to enter the Visual Basic Editor. The second is to launch the Visual Basic Editor from the
menu.
Next click on the command button and the VBA Editor will appear. Enter statement as shown in figure
OutPut is:
1
2.1 Data Types:
Excel VBA data types can be divided into 2 types. 1]Numeric Data Type
2] Non-Numeric DataType
2
2.3 Declaration of the variable:-
In excel VBA,we needs to declare the variables before using them by assigning
names and data types. You can declare the variables implicitly or explicitly
3.2.1 Implicit Declaration:-
We can use a variable without openly declare it if we assign an initial value to it.
MyFirstName=”John”
MyAge=32
Excel VBA automatically create 2 variables MyFirstName and MyAge as variants.
3.2.2 Explicit Declaration:
Implicit declaration of variable often leads to errors in writing code therefore it is better
to declare a variable explicitly.Variable are declare using the Dim Statement.
Syntax:
Dim variableName as DataType
Ex 2.1
Dim Password As String
Dim yourName As String
Dim firdtName As Integer
Dim lastName As Integer
Dim total As Integer
Dim BirthDay As Date
You may also combine them in one line, separating each variable with a comma, as follows:
Dim Password as String, Dim yourName as String, Dim firdtName as Integer.
For the fixed-length string, you have to use the format as shown below:
Dim VariableName as String*n
Ex 2.2
Private Sub CommandButton_Click()
Dim yourName As String, Dim BirthDay As Date, Dim Income As Currency
yourName=”Alex”
BirthDay=”1 April 1980”
Income=1000
Range(“A1”)=yourName
Range(“A2”)=BirthDay
Range(“A3”)=Income
End Sub
Output:
3
3.1 What is an Array:-
An array is a group of variables with the same data type and name. We differentiate
each item in the array by using subscript. If we need to enter one hundred names, instead of declaring
one hundred different variables, we need to declare only one array.
Output:
Ex 3.2:- You can also declare more than one array in a single line using Commas.
Private Sub CommandButton1_Click()
Dim StudentName(3) As String,StudentID(3) As String,StudentMark(3) As Single
For i=1 to 3
StudentID(i)=InputBox(“Enter Student ID”)
StudentName(i)=InputBox(“Enter Student Name”)
4
StudentMark(i)=InputBox(“Enter Student Mark”)
Cells(I,2)=StudentID(i)
Cells(i,1)=StudentName(i)
Cells(I,3)=StudentMarks(i)
Next
End Sub
When we run the program, 3 input boxes will appear consecutively
Output:-
5
End Sub
4.0 Operators:-
Operators are important in writing Excel VBA program code. They are used to calculate values,
perform certain operations, make comparisons and more. The operators can be divided into
three main categories:
Arithmetic
Comparison
Logical
6
MsgBox "Fail"
Endif
Table 4.2 Comparison Operators
Operator Meaning Example
< Less than MsgBox 2<3 returns true while MsgBox 4>5 returns false
If income>5000 or car>2
Or Logical Disjunction
thenStatus="Rich"
Similar to Or, except that it returns False if MsgBox 4 > 3 Xor 5 >2
Xor
both camparison values are true returns false
7
5.1: Subroutines
A Subroutine in Excel VBA is a procedure that performs a specific task and to return values, but
it does not return a value associated with its name. However, it can return a value through a
variable name. Subroutines are usually used to accept input from the user, display information,
print information, manipulate properties or perform some other tasks. It is a program code by
itself and it is not an event procedure because it is not associated with a runtime procedure or
an Excel VBA control such as a command button. It is called by the main program whenever it is
required to perform a certain task. Sub procedures help to make programs smaller and easier
to manage. A Subroutine begins with a Sub statement and ends with an End Sub statement.
Syntax:- for Declaration of Sub routine
SubsubProg(arguments)
Statements
End Sub
Sub FindHidden()
Dim hidden_txt as String
Hidden_txt=”@#%43&*”
MsgBox hidden_txt
End Sub
Ex 5.2:-
Private Sub CommandButton1_Click()
Call salary(10,300)
End Sub
8
5.2 Functions:-
A function is similar to a subroutine but the main purpose of the function is to accept a
certain input from the user and return a value which is passed on to the main program to finish the
execution.
There are 2 types of function 1] Built-in function 2] Function created by programmers or
user defined function.
1] built-in function
5.2.1 Message box
Syntax:
Message=MsgBox(Prompt, Style Value, Title)
Ex 5.1:-
Private Sub CommandButton1_Click()
Dim userMsg As String
userMsg=InputBox(“What is your message?”,”Message Entry Form”,”Enter your Message
here”,500,700)
If userMsg<>”” Then
MsgBox(userMsg)
Else
MsgBox(“No Message”)
End If
End Sub
Run : Input window will appear
9
5.3.1 Creating User-Defined Functions:-
Syntax:
Public Function functionName(Arg As datatype,…..)As datatype
Or
Private Function functionName(Arg As datatype,…..)As datatype
Public indicates that the function is applicable to the whole project while Private indicates that
the function is only applicable to a certain module or procedure.
10
6.0 Operators:-
We can write codes that can perform arithmetic operations using standard
arithmetic operators. However, for more complex mathematical calculations, we need to use
the built-in mathematical functions. Among them are Abs, Exp, Int, Fix, Rnd, Round, sqr and
more.
6.1 The Abs Function
The Abs function returns the absolute value(positive value) of a given number.
Syntax:-
Abs(Number)
Ex 6.1
Private Sub CommandButton1_Click()
Cells(1,1)=Abs(-100)
End Sub
6.2 The Exp Function
The Exp of a number x is the value of ex.
Syntax:-
Exp(Number)
Ex :
Private Sub CommandButton1_Click()
Cells(1,1)=Exp(1)
End Sub
Output:-
2.718282
11
6.4 The Rnd Function:-
The Rnd function returns a random value between 0 and 1. Rnd is very useful
when we deal with the concept of chance and probability.
Syntax:-
Rnd
Ex:-
Private Sub CommandButton1_Click()
Dim x As Integer
For x=1 To 10
nbps:Cells(x,1)=Rnd()
Next x
End Sub
Output:-
Display the program numbers between 0 and 1 from cell A1 to cell A10
7. Trigonometric Functions:-
7.1 The Sin Function:-
The Sin function returns the sine value of an angle. We need to convert the angle to radian as
Excel VBA cannot deal with angle in degree. The conversion is based on the following equation:
π radian= 180o
so 1o=π/180 radian
The issue is how to get the exact value of pi? We can use pi=3.14159 but it will not be accurate.
To get exact value of π, we use the arc tangent function, i.e. is Atn. Using the equation
tan(π/4)=1, so Atn(1)=π/4, therefore, π=4Atn(1)
Syntax:-
Sin(Angle in radian)
12
Ex:-
Private Sub CommandButton1_Click()
Dim pi As Single
Pi=4*Atn(1)
MsgBox(“Sin 90 is”& Round(Sin(pi/2),4))
End Sub
Output:-
13
In Cells(1,1)=computerual
Output:-
11
14
Ex 8.5:-
Private Sub cmdLen_Click()
Dim phrase As String
phrase=Cells(1,1).Value
Cells(6,1)=Len(phrase)
End Sub
Output :-
Cells(1,1)=”Visual Basic”
=12
Output of all string functions are in bellow
15
Ex 9.1:-
Private Sub CommandButton1_Click()
Cells(1, 1) = Format(8972.234, "General Number")
Cells(2, 1) = Format(8972.234, "Fixed")
Cells(3, 1) = Format(6648972.265, "Standard")
Cells(4, 1) = Format(6648972.265, "Currency")
Cells(5, 1) = Format(0.56324, "Percent")
End Sub
Output:-
16
Ex 9.2:-
Private Sub CommandButton1_Click()
Cells(1,1)=Format(781234.57,”0”)
Cells(2,1)=Format(781234.57,”0.0”)
Cells(3,1)=Format(781234.576,”0.00”)
Cells(4,1)=Format(781234.576,”#,##0.00”)
Cells(5,1)=Format(781234.576,”$#,##0.00”)
Cells(6,1)=Format(0.576,”0%”)
Cells(7,1)=Format(0.5768,”0.00%”)
End Sub
Output:-
Figure 9.2
17
Ex 10.1:-
Do you know how much you need to invest and how much you need to save monthly in order
to obtain $1,000,000 thirty years from now? Let’s assume fixed deposit interest rate is 4% per
annum and you are willing to save $100 monthly in the bank, you can write the following code
to find out the initial investment you need to fork out
10.2 FV
FV returns the amount ofmoney you will earn in future by putting in an initial
investment and continue to pay certain amount periodically. The amount is depending on the
interest rate and the duration. It relect time value of money.
Syntax:-
FV(Rate,Nper,Pmt,PV,Due)
Ex 10.2:-
In this example, you want to find the future value if your initial investment is $1,000,000, your
monthly payment is $100, interest rate 5% and the investment period is 30 years.
Private Sub CommandButton_Click()
Dim TheRate,PVal,Payment As Single
Dim NPeriod As Integer
TheRate=InputBox(“Enter the rate per annum”)
PVal=InputBox(“Enter initial investment amount”)
Payment=InputBox(“Enter number of year”)
NPeriod=InputBox(“Enter number of year”)
18
MsgBox(“The initial Investment is” & Round(FV(TheRate/12/100.NPerid * 12, -Payment-
PVal,0),2))
End Sub
Output:-
We place negative signs infront of payment and PVal as you are paying out the money.
10.3 Pmt:-
Pmt returns the amount of periodic payments you need to make for a certain PV & FV.
Syntax:-
Pmt(Rate,Nper,PV,FV,Due)
Ex 10.3:-
You borrowed a mortgage loan of 500,00 from the bank to buy a property. You have agreed to
pay back the loan in thirty years by a monthly instalment method at an interest rate of 4% per
annum.
Now you need to calculate the amount of monthly payment. In this case, Rate=4/100/12
(monthly rate),Nper=30*12=360 months, PV=500,000, FV=0 (loan settled) and due=0 as you
normally paying at end of the month.
Private Sub CommandButton1_Click()
Dim TheRate,PVal As Single
Dim NPeriod As Integer
TheRate=InputBox(“Enter the rate per annum”)
PVal=InputBox(“Enter Loan Amount”)
NPeriod=InputBox(“Enter number of years”)
MsgBox(“The monthly payment is”,& Round(Pmt(TheRate/12/100,nPeriod * 12, PVal,0,0),2))
End Sub
Output:-
It will produce a series of input boxes where the user can enter various values.
19
11.0 Date and Time Functions:-
We can use date and time functions to display system date and time , add and
substract data and time, converting string to date.
11.1 Now, Date, Day, Weekday, WeekdayName, Month, MonthName and Year Functions:-
Table 11.1 Date and Time Functions
Function Description
Day(Date) Returns the day of the month for the date specified in the argument
Weekday(Date) Returns weekday as an integer for the date specified in the argument
WeekdayName(Weekday(Date)) Returns the name of weekday for the date specified in the argument
WeekdayName(Weekday(Date) Returns the abbrieviated name of weekday for the date specified in
,True) the argument
Returns the month of the year in integer for the date specified in the
Month(Date)
argument
Returns the name of month of the year for the date specified in the
MonthName(Month(Date))
argument
Returns the abbrieviated name of month of the year for the date
MonthName(Month(Date))
specified in the argument
Year(Date) Returns the year in integer for the date specified in the argument
Ex 11.1:-
Private Sub CommandButton1_Click()
Cells(1, 2) = Now
Cells(2, 2) = Date
Cells(3, 2) = Day(Date)
Cells(4, 2) = Weekday(Date)
Cells(5, 2) = WeekdayName(Weekday(Date))
Cells(6, 2) = WeekdayName(Weekday(Date), "true")
Cells(7, 2) = Month(Date)
Cells(8, 2) = MonthName(Month(Date))
Cells(9, 2) = MonthName(Month(Date), "true")
Cells(10, 2) = Year(Date)
End Sub
20
11.2Time,Hour,Minute,Second & Timer Functions:-
Table 11.2 Time Functions
Function Description
21
12.0 Conditional and Logical Operators
12.1 Conditional operators:-
To control the Visual Basic program flow, we can use various conditional operators.
Basically, they resemble mathematical operators. Conditional operators are very powerful tools, they let
the VB program compare data values and then decide what action to take, whether to execute a
program or terminate the program .
Table 12.1: Conditional Operators
Operator Meaning
= Equal to
22
Ex 12.3:-
You place the CommandButton1 on the MS Excel spreadsheet and go into the VB
editor by clicking on the button.
I use randomize timer and the RND function to generate random numbers. In order to
generate integer between 0 to 100.
Private Sub CommandButton1_Click()
Dim Mark As Integer
Dim Grade As String
Randomize Timer
Mark=Int(Rnd*100)
Cells(1,1).Value=Mark
If Mark<20 And Mark>=0 Then
Grade=”F”
Cells(2,1).Value=Grade
ElseIf Mark<30 And Mark>=20 Then
Grade=”E”
Cells(2,1).Value=Grade
ElseIf Mark<40 And Mark>=30 Then
Grade=”D”
Cells(2,1).Value=Grade
ElseIf Mark<60 And Mark>=40 Then
Grade=”C”
Cells(2,1).Value=Grade
ElseIf Mark<80 And Mark>=60 Then
Grade=”B”
Cells(2,1).Value=Grade
ElseIf Mark<100 And Mark>=80 Then
Grade=”A”
Cells(2,1).Value=Grade
End If
End Sub
Output:-
23
12.4 Select Case:-
The Select Case control structure also involves decisions making but it is slightly
different from the If...Then...ElseIf control structure . The Select Case control structure
evaluates one expression for multiple values. Select Case is preferred when there exist multiple
conditions as using If...Then...ElseIf statements will become too messy.
Syntax:-
Select Case variable
Case value 1
Statement
Case value 2
Statement
Case value 3
Statement
Case Else
End Select
Ex12.4 :-
Private Sub CommandButton1_Click()
Dim Mark As Single
Dim Grade As String
Mark=Cells(1,1).Value
‘To set the alignment to center
Range(“A1:B1”).Select
With Selection.HorizontalAlignment=xlCenter
End With
Select Case Mark
Case 0 To 20
Grade=”F”
Cells(1,2)=Grade
Case 20 To 29
Grade=”E”
Cells(1,2)=Grade
Case 30 To 39
Grade=”D”
Cells(1,2)=Grade
Case 40 To 59
Grade=”C”
Cells(1,2)=Grade
24
Case 60 To 79
Grade=”B”
Cells(1,2)=Grade
Case 80 To 100
Grase=”A”
Cells(1,2)=Grade
Case Else
Grade=”Error!”
Cells(1,2)=Grade
End Select
End Sub
Output:-
13.0 Looping:-
Looping is a procedure that repeats many times until a condition is met. There
are two kinds of loops in Excel VBA. 1]For.......Next loop 2] Do...Loop
13.1 For....Next Loop:-
Syntax:-
For counter=startNumber to endNumber (Step increment)
Statements
Next
Ex 13.1:-
Private Sub CommandButton1_Click()
Dim i As Integer
For i=1 To 10
Cells(I,1).Value=i
Next
End Sub
25
You place the CommandButton 1 on the spreadsheet then click on it to go into the VB editor.
Output:-
Ex 13.2:-
Private Sub CommandButton1_Click()
Dim I,j As Integer
For i=1 To 10
For j=1 To 5
Cells(I,j).Value=i+j
Next j
Next i
End Sub
Output:-
26
14.0 Do Loop:-
15.1 Do Loop
There are four ways you can use the Do Loop as show below:
i) Do...........Loop While
(ii) Do until.............Loop
(iii) Do while............Loop
(iv) Do............Loop until
Ex 15.1 Arranging number in ascending order:-
Private Sub CommandButton1_Click()
Dim counter As Integer
Do
Counter=counter+1
Cells(counter,1)=counter
Loop While counter<10
End Sub
Output:-
27
Ex 14.3:-Program display the output X =A1 Y=X2=B1 X+Y =C1
Private Sub CommandButton1_Click()
Dim counter,sum As Integer
‘To set the alignment to center
Range(“A1:C11”).Select
With Selection.HorizontalAlignment=xlCenter
End With
Cells(1,1)=”X”
Cells(1,2)=”Y”
Cells(1,3)=”X+Y”
Do While counter < 10
Counter=counter + 1
Cells(counter +1, 1)=counter
Cells(counter+1, 2)=counter*2
Sum=Cells(counter+1, 1)+Cells(counter + 1,2)
Cells(counter + 1,3)=sum
Loop
End Sub
Output:-
28
14.4 While…Wend Loop:-
Syntax:-
While c ondition
Statement
Wend
Ex 14.4:-
we add list box to display series of numbers and the sum of those numbers.
Private Sub CommandButton1_Click()
ListBox1.Clear
Dim sum,n As Integer
While n <> 20
N=n + 1
Sum=sum + n
ListBox1.AddItem(n & vbTab & sum)
Cells(n + 1, 2)=n
Cells(n + 1, 3)=sum
Wend
End Sub
Output:-
29
15.0 Font & Background color
In this lesson, we can change the font color and the the background color of each
cell . Colors can be assigned using a number of methods in Excel VBA, but we shall focus on the
RGB function. The RGB function has three numbers corresponding to the red, green and blue
components. The range of values of the three numbers is from 0 to 255. A mixture of the three
primary colors will produce different colors.
Syntax:-
cells(i,j).Font.Color=RGB(x,y,z)
where x ,y , z can be any number between 1 and 255
Ex 15.1:-
Private Sub CommandButton1_Click()
cells(1,1).Font.Color=RGB(255,255,0)
End Sub
will change the font color to yellow
Syntax:- background color
Cells(i,j).Interior.Color=RGB(x,y,z)
Ex 15.2:-
Private Sub CommandButton1_Click()
Randomize Timer
Dim I,j,k As Integer
i=Int(255 * Rnd) + 1
j=Int(255 * Rnd) + 1
k=Int(255 * Rnd) + 1
Cells(1,1).Font.Color=RGB(I,j,k)
Cells(1,1).Interior.Color=RGB(j,k,i)
End Sub
Output:-
30
16.0: Objects
Excel VBA object is something like a tool or a thing that has certain functions and properties,
and can contain data. For example, an Excel Worksheet, cell in a worksheet, range of cells ,
font, a command button, and a text box is an object.
In order to view the VBA objects, you can insert a number of objects or controls into the
worksheet, and click the command button to go into the code window. The upper left pane of
the code window contains the list of objects you have inserted into the worksheet; you can
view them in the dropdown dialog when you click the down arrow. The right pane represents
the events associated with the objects, as shown in Figure 17.1 below.
31
16.2: Object Properties:-
An Excel VBA object has properties and methods. Properties are like the characteristics or
attributes of an object. For example, Range is an Excel VBA object and one of its properties is
value. We connect an object to its property by a period(a dot or full stop).
Ex16.1:-
Private Sub CommandButton1_Click()
Range("A1:A6").Value = 10
End Sub
Ex16.2:-
Private Sub CommandButton1_Click()
Range("A1:A6 = 10
End Sub
17.0: Methods
Methods are used to perform certain operations. For example, ClearContents is
a method of the range object. It clears the contents of a cell or a range of cells.
Ex 17.1:-
Private Sub CommandButton1_Click()
Range(“A1:A6”).ClearContents
End Sub
You can also write code to let the user select his or her own range of cells and clear the
contents by using the inputbox function,
Ex 17.2:-
Private Sub CommandButton1_Click()
Dim selectRng As String
selectRng=InputBox(“Enter your range”)
Range(selectRng).ClearContents
End Sub
To clear the contents of the entire worksheet, you can use
Sheet1.Cells.ClearFormats
To select a range of cells use Select method.
Syntax:-
Range(“A1:A5”).Select
32
Ex 17.3:-
Private Sub Commandbutton1_Click()
Range(“A1:A5”).Select
End Sub
This example allow user to specifies the range of cells to be selected.
Ex 17.4:-
Private Sub Commandbutton1_Click()
Dim selectRng As String
selectRng=InputBox(“Enter your range”)
Range(selectRng).Select
End Sub
To deselect the selected range, we can use the clear method.
Range(“CiRj:CmRn”).Clear
Ex 17.5:-
We insert two command buttons, the first one is to select the range and the second one is to
seselect the selected range.
Private Sub Commandbutton1_Click()
Range(“A1:A5”).Select
End Sub
Private Sub Commandbutton2_Click()
Range(“A1:A5”).Clear
End Sub
Ex 17.6:-AutoFill Method-
Private Sub Commandbutton1_Click()
Range(“A1”)=1
Range(“A2”)=2
Range(“A1:A2”).AutoFill Destination:=Range(“A1:A10”)
End Sub
Ex 17.7:-
Private Sub Commandbutton1_Click()
Cells(1,1).Value=”Monday”
Cells(2,1).Value=”Tuesday”
Range(“A1:A2”).AutoFill Destination:=Range(“A1:A10”),Type:=xlFillDays
End Sub
33
Ex 17.8:-Autofill cell using InputBox
Private Sub Commandbutton1_Click()
Dim selectRng As String
Sheet1.Cells.ClearContents
selectRng=InputBox(“Enter your range”)
Range(“A1”)=1
Range(“A2”)=2
Range(“A1:A2”).AutoFill Destination:=Range(selectRng)
End Sub
18.0 Method
Range is one of the most important and most commonly used Excel VBA object. In fact, we have
dealt with the Range object in previous lessons. Range has many methods and proeprties, we
will examine a few of them here.
18.1 The Select Method
The Range object contains two arguments that specifies a selected area on the spreadsheet.
Syntax:
Range(starting_cell,Ending_ Cell)
Ex 18.1:-
Private Sub CommandButton1_Click()
Range(“A1:C6”).Select
End Sub
18.2 The Columns Property
Syntax:
Range(starting cell, Ending cell).Columns(i).Select
Ex 18.2:-
Private Sub Commandbutton2_Click()
Range(Cells(1,1), Cells(6,3)).Columns(3).Select
End Sub
Output:-
34
18.3 Using With Range…..End With
You can also format font the cells in a particular column in terms of type, color,
bold, italic, underline and size using the With Range….End With Structure.it can also be used to
format other Range properties like background color.
Private Sub Commandbutton1_Click()
With Range(“A1:C6”).Columns(2)
.Font.ColorIndex=3
.Font.Bold=True
.Font.Italic=True
.Font.Underline=True
.Font.Name=”Times New Roman”
.Font.Size=14
.Interior.Color=RGB(255,125,175)
End With
End With
Output:- display background color and font color in column 2
35
Ex 18.5:- Using With Range….End With for Rows
Private Sub Commandbutton1_Click()
With Range(“A1:F3”).Rows(2)
.Font.ColorIndex=3
.Font.Bold=True
.Font.Italic=True
.Font.Underline=True
.Font.Name=”Times New Roman”
.Font.Size=14
.Interior.Color=RGB(255,125,175)
End With
End With
Output:-
Output:-
36
18.6 The Formula Property:
You can use the formula property of the Range object to write your own
customized formula.
Private Sub CommandButton1_Click()
Range(“A1:B3”).Columns(3).Formula=”=A1+B1”
End Sub
Output:-
Or
Range(“A1:B3”).Columns(3).Formula=”=Sum(A1:B1)”
37
19.0 Mode
The program computes the mode for every row in the range A1:E4 and displays
them in column F. It also makes the font bold and red in color.
Ex:-
Private Sub CommandButton1_Click()
Range(“A1:E4”).Columns(6).Formula=”=Mode(A1:E1)”
Range(“A1:E4”).Columns(6).Font.Bold=True
Range(“A1:E4”).Columns(6).Font.ColorIndex=3
End Sub
Output:-
Ex 20.1.2
Count property returns the number of worksheets in an opened workbook.
Private Sub CommandButton1_Click()
MsgBox Worksheets.Count
End Sub
38
Output:-
Ex 20.1.3:-
The count property in this example will returns the number of columns in the worksheet.
Private Sub Worksheets(1).Columns.Count
End Sub
Output:-
Ex 20.1.4:-
The count property in this example will return the number of rows in the worksheet.
Private Sub CommandButton1_Click()
MsgBox Worksheets(1).Rows.Count
End Sub
Output:-
39
Ex 20.2.2
The select method associated with worksheet lets the user select a particular worksheet.
Private Sub CommandButton1_Click()
Worksheets(2).Select
End Sub
The select method can also be used together with the worksheet properties Cells,
Columns and Rows
Ex 20.2.3
Private Sub CommandButton1_Click()
Worksheets(1).Cells(1).Select
End sub
Ex 20.2.4
Private Sub CommandButton1_Click()
Worksheets(1).Columns(1).Select
End sub
Ex 20.2.4
Private Sub CommandButton1_Click()
Worksheets(1).Rows(1).Select
End sub
21.1 CheckBox
It allows the user to select one or more items by checking the check box or check
boxes concerned. One of most important properties of the check box is Value. If the check box
is selected or checked, the value is true, while if it is not selected or unchecked, the Value is
False.
Ex 22.1
Private Sub CommandButton1_Click()
If CheckBox1.Value = True And CheckBox2.Value = False Then
MsgBox "Quantity of apple sold is" & Cells (2, 2).Value
ElseIf CheckBox2.Value = True And CheckBox1.Value = False Then
MsgBox "Quantity of orange sold is " & Cells(2, 3).Value
Else
MsgBox "Quantity of Fruits sold is" & Cells (2, 4).Value
End If
End Sub
40
Output:-
41
21.3 List Box
The function of the List Box is to present a list of items where the user can click
and select the items from the list. To add items to the list, we can use the AddItem method. To
clear all the items in the List Box, you can use the Clear method.
Ex 21.3.1
Private Sub CommandButton1_Click()
For x = 1 To 10
ListBox1.AddItem "Apple"
Next
End Sub
'To clear the List Box
Private Sub CommandButton2_Click()
For x = 1 To 10
ListBox1.Clear
Next
End Sub
Output:-
21.4 ComboBox
The function of Combo Box is also to present a list of items where the user can
click and select the items from the list. However, the user needs to click on the small arrowhead
on the right of the combo box to see the items which are presented in a drop-down list. In
order to add items to the list, you can also use the AddItem method.
42
Ex 21.4.1
Private Sub CommandButton1_Click()
ComboBox1.Text=”Apple”
For x=1 To 10
ComboBox1.AddItem “Apple”
Next
End Sub
To clear the combo Box
Private Sub CommandButton2_Click()
ComboBox1.Clear
End Sub
Output:-
43
Cells(1,1)=”Orange”
Cells(1,1).Font.Color=vbBlue
End If
End Sub
Output:-
44
Output:-
To separate the pie chart into slices, you can add this to the code
ActiveChart.SeriesCollection(1).Explosion=10
After adding this code output shows like in below figure.
45
ActiveChart.HasTitle=True
ActiveChart.ChartTitle.Text=”MyC Chart”
End Sub
Output:-
It has abuilt-in parameters to define the types of charts that can be drawn on a spreadsheet.
You can refer to the parameters as the ChartType properties.
Property Chart Type
46
For example, if you change the ChartType property to xlLine using the code
ActiveChart.ChartType=xlLine
You can get the line graph like below:
22.3 Animation
Animation can be achieved by changing the position of an object continuously
using a looping sub procedure. Two properties or functions that are required to change the
positions or coordinates of the object are the Left and Top properties. The Left property
specifies the distance of the left edge of the object in pixel from the left border of the screen
and the Top property specifies the distance of the top edge of the object from the top border of
the screen.
Ex:-, the following code makes the object move from left to right then back to left again
repeatedly until the user press the stop button. The reset button move the object back to the
starting position.
Private Sub StartButton_Click()
repeat:
With VBAProject.Sheet.Image1
.Left=.Left+1
DoEvents
If .Left>200 Then.Left=1
End With
GoTo repeat
End Sub
Output:-
47
If you wish to move the object up and down, change the above code by replacing the property
left to Top, the code appear as follows:
Private Sub StartButton_Click()
repeat:
With VBProject.Sheet1.Image1
.Top=.Top + 1
DoEvents
If .Top>200 Then .Top=1
End With
GoTo repeat
End Sub
If you wish to make the object move diagonally, then use the properties Top and Left at the
same time
Private Sub StartButton_Click()
repeat:
With VBAProject.Sheet1.Image1
.Top=.Top + 5
.Left=.Left + 5
DoEvents
If .Top>200 Then .Top=1
If .Left>200 Then .Left=1
End With
GoTo repeat
End Sub
48
Examples
1]
Sub Macro1 ()
For n = 1 To 5
Cells(n, 1) = n
Next n
End Sub
2]Yes No type questions
Sub MacroName()
MsgBox ("Hello World!")
End Sub
3]
Sub MacroName()
Dim Answer As String
Answer = MsgBox("Are you sure you want to delete the cell values ?",
vbQuestion + vbYesNo, "Delete cell")
If Answer = vbYes Then
ActiveCell.ClearContents
End If
End Sub
4]
Sub MacroName()
Dim CellValue As Integer
CellValue = ActiveCell.Value
If CellValue > 20 Then
With Selection.Font.Color = -16776961
End With
Else
With Selection.Font.ThemeColor = xlThemeColorLight2'.TintAndShade = 0
End With
End If
End Sub
5]
Sub MacroName()
Dim CellValue As Integer
CellValue = ActiveCell.Value
Select Case CellValue
Case 60 To 200
MsgBox "The person is old"
Case 30 To 59
MsgBox "The person is adult"
Case 18 To 29
MsgBox "The person is young"
Case 0 To 17
MsgBox "The person is a child"
Case Else
MsgBox "Unknown age"
End Select
End Sub
6]Prime no
Dim divisors As Integer, number As Long, I As Long
Divisors=0
Number=InputBox(“Enter a number”)
For i=1 to number
49
If number Mod i=0 Then
Divisors= divisors + 1
End If
Next i
If divisors=2 Then
MsgBox number & “ is a prime number
Else
MsdBox & “ is not a prime number
End If
Result for 104729:
nd
7]Find 2 highest value
Private Sub CommandButton1_Click()
Dim rng As Range,cell As Range
Dim highestValue As Double, secondHighestValue As Double
Set rng = Selection
highestValue = 0
secondHighestValue = 0
For Each cell In rng
Next cell
If cell.value > secondHighestValue And cell.Value < highestValue Then
secondHighestValue = cell.Value
MsgBox “Second Highest Value is “ & secondHighestValue
End if
End Sub
8] Sum by Color
Private Sub CommandButton1_Click()
Dim toReceive As Integer, I As Integer
toReceive = toReceive + Cells(I, 1).Value
End If
Next i
MsgBox “Still to receive “ & toReceive & “ dollars “
End Sub
9] Delete Black Cell
Private Sub CommandButton1_Click()
Dim counter As Integer, I As Integer
Counter = 0
For I = 1 To 10
If Cells(i, 1).Value <> “” Then
Cells(counter + 1, 2).Value = Cells(I, 1).Value
counter = counter + 1
End If
Next i
Range(“A1:A10”).Value = “”
Range(“A1:A10”).Value = Range(“B1:B10”).Value
Range(“B1:B10”).Value = “”
10]Square root using loop
Private Sub CommandButton1_Click()
Dim rng As Range, cell As Range
Set rng = Range(“A1:A3”)
For Each cell In rng
Next cell
Cell.Value = cell.Value * cell.Value
Set rng = Range(“A1:A3”)
Set rng = Selection
End Sub
11]create Pattern
50
Dim i As Integer, j As Integer
For i= 1 To 5 Step 2
For j=1 To 5 Step 2
Cell(i, j).Interior.ColorIndex = 15
Next i
Next j
The only thing we need to do, is color the cells which are offset by 1 row below and 1 column to the right
of the cells already colored. Add the following code line to the loop.
Cells(I, j).Offset(1, 1).Interior.ColorIndex= 15
12]Calculate N=
3
k2 + 6k +
Sum Type=
Tk = 1 All
2.003529
9k + 7 Sum=
k Tk
1 0.5
2 0.68
3 0.823529412
Private Sub CommandButton1_Click()
Dim i, term, N, stepSize As Integer
Dim sumType As String
i=0
N = Range("C2").Value
sumType = Range("C3").Value
Range("A8:B1000").Value = ""
Range("C6").Value = ""
i=i+1
Next term
End Sub
51
13]
52
Private Sub commandbutton1_click()
Dim fullname As String, commaposition As Integer, i As Integer
For i = 2 To 7
fullname = Cells(i, 1).value
commaposition = InStr(fullname, ",")
Cells(i, 2).value = Mid(fullname, commaposition + 2)
Cells(i, 3).value = Left(fullname, commaposition - 1)
Next i
End Sub
15] Reverse the string
Private Sub commandbutton1_click()
Dim text As String, reversedText As String, length As Integer, i As Integer
text = InputBox("Enter the text you want to reverse")
length = Len(text)
For i = 0 To length - 1
reversedText = reversedText & Mid(text, (length - i), 1)
Next i
MsgBox reversedText
End Sub
53