Vous êtes sur la page 1sur 53

Introduction of Macro:-

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.

1.1 Creating Excel VBA Using the Command Button:-


To create an Excel VBA using the command button, you need to place it on the
spreadsheet. In order to access the command button, you need to click developer on the MS Excel menu
bar and then click on the Insert and select the command button and place it on the spreadsheet. As
shown in figure.

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

1]Numeric Data Type:


Numeric data types are types of data that consist of numbers,which can be
computed mathematically with various standard arithmetic operators such as
add,minus,multiply,divide and so on.

2] Non-Numeric Data Type


Data Type Storage Range
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
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

2.2 The Concept of Variables:-


Variables are like mail boxes in the post office. The content of the variables changes every now
and then, just like the mail boxes. In Excel VBA, variables are areas allocated by the computer
memory to store data. Like the mail boxes, each variable must be given a name.
The following are the rules when naming the variables in Excel VBA
 They must not exceed 40 characters
 They must contain only letters, numbers and underscore chacaters
 No spacing is allowed
 It must not begin with a number
 Period is not permitted
Table 2.1 : Examples of valid and invalid variable names
Valid Name Invalid Name
My_Car My.Car
ThisYear 1NewBoy
Long_Name_Can_beUSE He&HisFather *& is not acceptable
Group88 Student ID * Spacing not allowed

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.

3.2.1 One Dimensional Array:


The statements to declare a one dimensional array in Excel VBA is as follows:
Syntax:
Dim arrayName (index) as dataType or
Dim arrayName (first index to last index) as dataType
For example:
Dim StudentName(10) as String
Dim StudentName(1 to 10) as String
Dim StudentMark(10) as Single
Dim StudentMark( 1 to 10) as Single
Note: - InputBox is created automatically when below code will run.
Ex 3.1:-
Private Sub CommandButton1_Click()
Dim i as integer
Dim StudentName (1 to 5) As String
For i= 1 to 5
StudentName (i) =InputBox(“Enter Student Name”)
Cells (I,1)=StudentName(i)
Next
End Sub

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:-

3.2.2 Two Dimensional Array:


Data are usually oraganized & arranged in table form,this is where the
multidimensional array come into play. Two dimensional array can be represented by a table
that contains rows and columns where one index represents the rows and the other index
represent the columns.
Syntax:
Dim arrayName(num1, num2) as datatype
Ex.
Private Sub CommandButton1_Click()
Dim SalesVolume(2 to 6, 2 to 3) as Single
Dim SalesPerson as Integer,Day as Integer
For SalesPerson=2 to 6
For Day=2 to3
SalesVolume(SalesPerson, Day)=InputBox(“Enter Sales Volume of ” & “SalesPerson “ &
(SalesPerson-1)& “Day “&(Day-1))
Cells(SalesPerson, day)=SalesVolume(SalesPerson, Day)
Next Day
Next SalesPerson

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

4.1 Arithmetic Operators


Arithmetic operators are used to perform mathematical operations in Excel VBA.
Table 4.1 Arithmetic Operators
Operator Mathematical function Example

^ Exponential MsgBox 2^4 gives a value of 16

* Multiplication MsgBox 4*3 gives a value of 12,

/ Division MsgBox 12/4 gives a value of 3

Modulus (returns the remainder from an


Mod MsgBox 15 Mod 4 gives value of 3
integer division)

\ Integer Division(discards the decimal places) MsgBox 19\4 gives a value of 4

MsgBox "Excel"&"VBA 2010" or "Excel"+"VBA


+ or & String concatenation
2010" produces a new string "Excel VBA 2010"

MsgBox is a built-in function of excel VBA that displays a message.

4.2 Comparison Operators


Comparison operators are often used in writing code that require decisions making. For
example,
If mark>50 then
MsgBox "Pass"
Else

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

<= Less than or equal to MsgBox 3<=4 returns true

> Greater than MsgBox 5>4 returns true

>= Greater than or equal to MsgBox 10>=9 returns true

= Equal to MsgBox 10=10 returns true

<> Not Equal to MsgBox 9<>10 returns true

4.3 Logical Operator:-


Logical operator are also used in writing decision making codes by comparing
values or expressions.

4.3 Table Logical Operator:-

Operator Meaning Example

If A>=80 And B<101


And Logical Conjunction
thenGrade="A"

If income>5000 or car>2
Or Logical Disjunction
thenStatus="Rich"

MsgBox Not (3 > 4)returns


Not Logical negation
true

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

Syntax:- for calling Sub routine using the Call keyword.


Sub MainProg( )
Call SubProg()
End Sub
A subroutine is different from a function that it does not return a value directly. You can include
parameters in a subroutine.
Ex 5.1:-
Private Sub CommandButton1_Click()
Call FindHidden
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

Sub salary(wage As Single, hours As Single)


MsdBox wage*hours
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)

5.2.2 InputBox Function:


An InputBox() function displays a message box where the user can enter a value or a
message in the form of text.
Syntax:
myMessage=InputBox(Prompt, Title, default_text, x-positioin, y-position)

myMessage :- is a variant data type.


Prompt :- represents he message displayed normally as a question asked.
Title :-represent the title of the Input Box
Default_Text:-represent the default text that appears in the field where users can use it as his intended
input or he may change to the message he wish to key in.
x-position & y-position:-coordinate of the input box.

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.

Private Sub CommandButton1_Click()


Call CubRoot(108)
Range(“A1”)=CubRoot(108)
End Sub
Output:
Figure 5.3 The value of cube root for the number in cell C4 will appear in cell D4.

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

6.3 The Int Function:


Int is the function that converts a number into an integer by truncating its
decimal part and the resulting integer is the largest integer that is smaller than the number.
Syntax:-
Int(Number)
Ex:-
Private Sub CommandButton1_Click()
Cells(1,1)=Int(2.4)
Cells(2,1)=Int(4.8)
Cells(3,1)=Int(-4.6)
Cells(4,1)=Int(0.32)
End Sub
Output:-
A
1 2
2 4
3 -5
4 0

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

6.6 The Round Function:-


Roundup a number to a certain number of decimal places.
Syntax:-
Round(n,m)
Ex:-
Round(7.2567,2)
Output:-
7.26

6.7 The Sqr Function:-


Sqr is the function that computes the square root of a number
Syntax:-
Sqr(Number)
Ex:-
Sqr(4)=2, Sqr(9)=3

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:-

7.2 The Cos Function:-


The Cos function returns the cosine value of an angle.
Syntax:-
Cos(Angle in radian)
Ex:-
Private Sub CommandButton1_Click()
Dim pi As Single
Pi=4*Atn(1)
MsgBox(“Cos 60 is” & Round(Cos(pi/3),4))
End Sub
Output:-

8.0 String Functions:-


8.1 The InStr function
InStr is a function that looks for and returns the position of a substring in a phrase
Ex 8.1:-
Private Sub cmdInstr_Click()
Dim phrase As String
phrase = Cells(1, 1).Value
Cells(4, 1) = InStr(phrase, "ual")
End Sub

13
In Cells(1,1)=computerual
Output:-
11

8.2 The Left Function:-


Left is the function that extract the characters from a phrase, starting from the left.
Ex 8.2:-
Private Sub cmdLetf_Click()
Dim phrase As String
phrase=Cells(1,1).Value
Cells(2,1)=Left(phrase,4)
End Sub
Output:-
In cells(1,1)=”Visual Basic”
=Visu

8.3 The Right Function:-


Right is a function that extract characters from a phrase,starting from the Right.
Ex 8.3:-
Private Sub cmdRight_Click()
Dim phrase As String
phrase=Cells(1,1).Value
Cells(3,1)=Right(phrase,5)
End Sub
Output:-
Cells(1,1)=”Visual Basic”
=Basic

8.4 The Mid Function


Mid is a function that extracts a substring from a phrase, starting from the
position specified by the second parameter in the bracket.
Ex 8.4:-
Private Sub cmdMid_Click()
Dim phrase As String
phrase=Cells(1,1).Value
Cells(5,1)=Mid(phrase,8,3)
End Sub
Output:-
Cells(1,1)=”Visual Basic”
=Bas

8.5 The Len Function:


Len is a function that retuns the length of a phrase(including empty space in
between)

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

9.0 Format Function:-


The Format function in Excel VBA can display the numeric values in various formats .
There are two types of Format functions:- 1] built-in Format function 2] user-defined Format function.
9.1 Built-in Format function
Syntax:-
Format (n, "style argument")
where n is a number and the list of style arguments are listed in Table 9.1

Style argument Explanation Example

General Number To display the number without having separators Format(8972.234,


between thousands. “General
Number”)=8972.234
Fixed To display the number without having separators Format(8972.234,
between thousands and rounds it up to two decimal “Fixed”)=8972.23
places.
Standard To display the number with separators or separators Format(6648972.265,
between thousands and rounds it up to two decimal “Standard”)=
places. 6,648,972.27
Currency To display the number with the dollar sign in front, has Format(6648972.265,
separators between thousands as well as rounding it up “Currency”)=
to two decimal places. $6,648,972.27
Percent Converts the number to the percentage form and Format(0.56324,
displays a % sign and rounds it up to two decimal places. “Percent”)=56.32 %

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:-

9.2 The User-Defined Format Function:-


Synatax:-
Format(n,”user’s format”)
Ex 9.2:- listed in Table 9.2

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

10.0 Financial Functions:


Financial functions that can be used for accounting and financial calculations. In
this lesson, we shall deal some of those functions that perform basic financial calculations.
10.1 PV
PV returns the present value of a certain amount of money a person needs to invest in order to
earn a certain amount of money in the future(future value), based on the interest rate and the
number of years this amount of money is kept. Additionally, it can also return the present value
of an annuity which means the present value of a series of payments in the future
Syntax:-
PV(Rate, Nper, Pmt, FV, Due)
The parameters in the parentheses are explained below:
Rate - Interest rate per period
Nper - Number of payment periods
Pmt - Amount of periodic payment for an annuity
FV - Future value
Due - Indicates when the payment is due. Its value is 1 for beginning of month and 0 for end of
the month

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

Private Sub CommandButton1_Click()


Dim TheRate,FuVal,Payment As Single
Dim Nperiod As Integer
TheRate=InputBox(“Enter the rate per annum”)
FuVal=InputBox(“Enter future value”)
Payment=InputBox(“Enter amount of monthly payment”)
NPeriod=InputBox(“Enter number of years”)
MsgBox(“The Initial Investment is” & Round(PV(TheRate/12/100, NPeriod * 12,
Payment,FuVal,1),2))
End Sub
Output :-
Running the program will produce a series of input boxes where the user can enter various
values.

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

Now returns current system date and time

Date returns current system date

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

Time Returns the current system time

Hour Returns the hour from its argument

Minute Returns the minute from its argument

Second Returns the second from its argument

Timer Returns the number of seconds since midnight


Ex 11.2:-
Private Sub CommandButton1_Click()
Cells(1,2)=Time
Cells(2,2)=Hour(Time)
Cells(3,2)=Minute(Time)
Cells(4,2)=Minute(Time)
Cells(5,2)=Timer
End Sub
Output:-

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

> More than

< Less Than

>= More than or equal

<= Less than or equal

<> Not Equal to

12.2 Logical Operator:-


Table 12.2 Logical Operators
Operator Meaning

And Both sides must be true

or One side or other must be true

Xor One side or other must be true but not both

Not Negates truth

12.3 Using If….Then…..Else Statements with Operators:-


To control the program flow, we shall use If…..Then…Else statement together
with the conditional operators and logical operators.
Syntax:-
If condition Then
Statements
ElseIf
Statements
ElseIf
Statements
Else
EndIf

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:-

Ex 14.2:- Arranging number in descending order


Private Sub CommandButton1_Click()
Dim counter As Integer
Do Until counter=10
Counter=counter+1
Cells(counter,1)=11-counter
Loop
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.

16.1:Excel VBA Objects:-

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

18.4 The Row property:-


Syntax for the property is similar to that of the Columns property, you just need
to replace Columns with rows.
Private Sub CommandButton2_Click()
Range(“A1:F3”).Rows(3).Select
End Sub
Output:-

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:-

18.5 Using the Set keyword to Declare Range


We can write the code such that it can accept range input from the user and
then change the mark to blue if it is more than or equal to 50 and change it to red if the mark is
less than 50
Ex 18.5
Private Sub CommandButton1_Click()
Dim Rng,Cell As Range, selectRng As String
selectRng=Inputbox(“Enter your range”)
set Rng=Range(selectRng)
for Each Cell In Rng
If Cell.Value>=50 Then
Cell.Font.ColorIndex=5
Else
Cell.Font.ColorIndex=3
End If
Next Cell
End Sub

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)”

Ex 18.7 for Average


Private Sub CommandButton1_Click()
Range(“A1:B3”).Columns(3).Formula=”=Average(A1:B1)”
End Sub

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:-

20.1 The WorkSheet Propertes


Similar to the Range Object, the Worksheet has its own set of properties and
methods. Some of the common properties of the worksheet are name, count, cells, columns,
rows and columnWidth.
Ex 20.1.1:-
Private Sub CommandButton1_Click()
MsgBox Worksheets(1).Name
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:-

20.2 The Worksheet Methods


Some of the worksheet methods are add, delete, select, SaveAs, copy, paste.
Ex 20.2.1
Private Sub CommandButton1_Click()
Workdheets.Add
End Sub
Private Sub CommandButton2_Click()
Worksheets(1).Delete
End Sub

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:-

21.2 Option Button


The option button control also lets the user selects one of the choices. However,
two or more option buttons must work together because as one of the option buttons is
selected, the other option buttonwill be deselected.
Ex 21.2.1
Private Sub CommandButton1_Click()
If OptionButton1.Value=True Then
MsgBox “Gender is Male”
Else
MsgBox “Gender is Female”
End If
End Sub
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:-

21.5 Toggle Button


Toggle button lets the user switches from one action to another alternatively.
When the Toggle Button is being depressed, the value is true and when it is not depressed, the
value is false. By using the If and Else code structure, we can thus switch from one action to
another by pressing the toggle button repeatedly.
Ex 21.5.1
Private Sub ToggleButton1_Click()
If ToggleButton1.Value=True Then
Cells(1,1).Font.Color=vbRed
Else

43
Cells(1,1)=”Orange”
Cells(1,1).Font.Color=vbBlue
End If
End Sub
Output:-

22.1 Creating a Pie Chart


To create a pie chart in a spreadsheet, first of all you need to enter a range of
data in spreadsheet. After entering the data, you need to name the range by right-clicking the
range and clicking define name in the pop-up menu. Name the chart MyChart Now insert a
command button and then click it to enter the following code in the Excel VBA editor
Private Sub CommandButton1_Click()
ActiveSheet.Shapes.AddChart.Select
ActiveSheet.Shapes(1).Top = 10
ActiveSheet.Shapes(1).Left = 10
ActiveChart.ChartType = xl3DPie
ActiveChart.PlotArea.Select
ActiveChart.SetSourceData Source:=Range("MyChart")
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = "My Chart"
End Sub

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.

22.2 Creating a bar Graph


To draw a bar graph, you just need to change the ChartType to xl3DColumn.
Private Sub CommandButton2_Click()
ActiveSheet.Shapes.AddChart.Select
ActiveSheet.Shapes(1).Top=10
ActiveSheet.Shapes(1).Left=10
ActiveChart.ChartType=xl3DColumn
ActiveChart.PlotArea.Select
ActiveChart.SetSourceDate source:=Range(“MyChart”)

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

xlArea Area Chart

xlBar Bar Chart

xlColumn Column Chart

xlLine Line Chart

xlPie Pie Chart

xlXYScatter XY Scatter Chart

xl3DArea 3D Area Chart

xl3DBar 3D Bar Chart

xl3DColumn 3D Column Chart

Xl3DLine 3D Line Chart

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 = ""

Select Case sumType


Case Is = "All"
stepSize = 1
Case Is = "Odd"
stepSize = 2
Case Else
MsgBox "Enter a valid expression in cell C3"
End
End Select

For term = 1 To N Step stepSize


Cells(8 + i, 1).Value = term
Cells(8 + i, 2).Value = (term ^ 2 + (6 * term) + 1) / ((9 * term) + 7)

Range("C6").Value = Range("C6").Value + Cells(8 + i, 2).Value

i=i+1
Next term
End Sub

51
13]

Private Sub CommandButton1_Click()


Dim limit As Double, weight As Double, value As Double, totalWeight As Double, maximumValue As Double
Dim i, j, k, l, m As Integer
limit = Range("D6").value
maximumValue = 0
For i = 0 To 1
For j = 0 To 1
For k = 0 To 1
For l = 0 To 1
For m = 0 To 1
weight = 12 * i + 2 * j + 1 * k + 1 * l + 4 * m
value = 4 * i + 2 * j + 2 * k + 1 * l + 10 * m
If value > maximumValue And weight <= limit Then
Range("B4").value = i
Range("C4").value = j
Range("D4").value = k
Range("E4").value = l
Range("F4").value = m
totalWeight = weight
maximumValue = value
End If
Next m
Next l
Next k
Next j
Next i
Range("B6").value = totalWeight
Range("B8").value = maximumValue
End Sub
14] Seprate string

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

Vous aimerez peut-être aussi