logical operator and
TRANSCRIPT
-
7/24/2019 Logical Operator And
1/77
Logical Operator And
Place a command buttonon your worksheet and add the following code lines:
Dim score1 As Integer, score2 As Integer, result As String
score1 = ange!"A1"#$%aluescore2 = ange!"&1"#$%alue
If score1 '= () And score2 ' 1 *hen result = "+ass"lse result = "fail"nd If
ange!"-1"#$%alue = result
Logical Operator Or
Place a command buttonon your worksheet and add the following code lines:
Dim score1 As Integer, score2 As Integer, result As String
score1 = ange!"A1"#$%aluescore2 = ange!"&1"#$%alue
If score1 '= () .r score2 ' 1 *hen result = "+ass"lse result = "fail"nd If
ange!"-1"#$%alue = result
Logical Operator Not
Place a command buttonon your worksheet and add the following code lines:
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
2/77
Dim score1 As Integer, score2 As Integer, result As String
score1 = ange!"A1"#$%aluescore2 = ange!"&1"#$%alue
If score1 '= () And /ot score2 = 1 *hen result = "+ass"lse result = "fail"nd If
ange!"-1"#$%alue = result
Place a command buttonon your worksheet and add the following code lines:
1$ 0irst, declare two ariables$ .ne ariable of ty+e Integer named score and one ariable of ty+eString named result$
Dim score As Integer, result As String
2$ e initiali3e the ariable score with the alue of cell A1$
score = ange!"A1"#$%alue
4$ Add the Select -ase structure$
Select -ase score -ase Is '= 5) result = "ery good" -ase Is '= 6) result = "good" -ase Is '= () result = "sufficient" -ase lse result = "insufficient"nd Select
Tax Rates
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
3/77
&elow we will look at a +rogram in Excel VBAthat calculates the ta7 on an income$ *he
following tax ratesa++ly to indiiduals who are residents of Australia$
Taxable income Tax on this income
) 8 9(,))) /il
9(,))1 8 94,))) 1c for each 91 oer 9(,)))
94,))1 8 95),))) 9;,4) +lus 4)c for each 91 oer 94,)))
95),))1 8 915),))) 916,5) +lus 45c for each 91 oer 95),)))
915),))1 and oer 9,5) +lus ;c for each 91 oer 915),)))
Situation:
1$ 0irst, we declare two double ariables$ .ne double ariable we call income, and one double
ariable we call ta7$
Dim income As Double
Dim tax As Double
2$ e initiali3e the ariable income with the alue of cell A2 and round it$
income = Round(Range("A2").Value)
4$ e +lace the rounded alue into cell A2 again$
Range("A2").Value = income
;$ e use the Select -asestatement to calculate the ta7 on an income$ 7cel %&A uses income to
test each subse
-
7/24/2019 Logical Operator And
4/77
Select Case income
Case Is >= 1!!!1
tax = ! # !.$ % (income & 1!!!!)
Case Is >= !!!1
tax = 1'! # !. % (income & !!!!)
Case Is >= !!1 tax = $! # !. % (income & !!!)
Case Is >= !!1
tax = !.1 % (income & !!!)
Case *lse
tax = !
*nd Select
7am+le: if income is 46))), ta7 e !46)))84)))# = ;4) ()) = 9;?)
$ e write the alue of the ariable ta7 to cell &2$
Range("+2").Value = tax
($ Place this code in a command button and test it$
esult:
1$ 0irst, we declare three ariables$ .ne Integer ariable we call diisors, one @ong ariable wecall number and one @ong ariable we call i$ e use @ong ariables here because @ong ariableshae larger ca+acity than Integer ariables$
Dim diisors As Integer, number As @ong, i As @ong
2$ e initiali3e two ariables$ e initiali3e the ariable diisors with alue )$ e use theIn+ut&o7 function to get a number from the user$
diisors = )number = In+ut&o7!"nter a number"#
-
7/24/2019 Logical Operator And
5/77
After the user has entered a number, we want to check whether this number is a +rime number ornot$ emember, a +rime number has e7actly two distinct number diisors: 1 and itself$
4$ e start a 0or /e7t loo+$
0or i = 1 *o number
;$ /ow comes the most im+ortant +art of the +rogram$ *o calculate the number of diisors of anumber, we use the od o+erator$ *he od o+erator gies the remainder of a diision$ So 6 mod2 would gie 1$ 6 is diided by 2 !4 times# to gie a remainder of 1$ .nly if "number mod iBe
-
7/24/2019 Logical Operator And
6/77
esult for 1);62?:
Find Second Highest Value
&elow we will look at a +rogram in Excel VBAthat finds the second highest value$
Situation:
1$ 0irst, we declare two ange obects and two ariables of ty+e Double$ e call the ange
obects rng and cell$ .ne double ariable we call highest%alue, and one double ariable we call
secondEighest%alue$
Dim ,ng As Range- cell As Range
Dim igestValue As Double- second/igestValue As Double
-
7/24/2019 Logical Operator And
7/77
2$ e initiali3e the ange obect rng with the selected range and the two Double ariables with
alue )$
Set ,ng = Selection
igestValue = !
second/igestValue = !
4$ 0irst, we want to find the highest alue$ e want to check each cell in a randomly selected
range !this range can be of any si3e#$ In 7cel %&A, you can use the 0or ach /e7t loo+ for this$
Add the following code lines:
0ind /igest Value
o, *ac cell In ,ng
ext cell
/ote: rng and cell are randomly chosen here, you can use any names$ emember to refer to these
names in the rest of your code$ *he green line is a comment and is only added here to +roide
information about this +iece of code$
;$ e check each cell in this range$ If itBs higher than highest%alue, we write the alue to the
ariable highest%alue$ Add the following code line to the loo+$
I3 cell.Value > igestValue 4en igestValue = cell.Value
/ote: the first alue is always higher than highest%alue because the starting alue of
highest%alue is )$
$ Second, we want to find the second highest %alue$ e add another 0or ach /e7t loo+$
0ind Second /igest Value
o, *ac cell In ,ng
ext cell
($ e check each cell in the selected range again$ If itBs higher than secondEighest%alue and
lower than highest%alue, we write the alue to the ariable secondEighest%alue$ Add the
following code line to the loo+$
I3 cell.Value > second/igestValue And cell.Value 5 igestValue 4en
second/igestValue = cell.Value
6$ 0inally, we dis+lay the second highest alue using a sg&o7$
-
7/24/2019 Logical Operator And
8/77
6sg+ox "Second /igest Value is " 7 second/igestValue
5$ Place your macro in a command button, select the numbers, and click on the command button$
esult:
Sum by Color
&elow we will look at a +rogram in Excel VBAthat sums numbers by color$
Situation:
Fou hae lended money to two twele +eo+le$ Some +eo+le hae gien it back !in black# and
some still owe you money !red#$ Fou want to know how much money you still receie$
-
7/24/2019 Logical Operator And
9/77
1$ 0irst, we declare two ariables of ty+e Integer$ .ne named toeceie and one named i$ e
initiali3e the ariable toeceie with alue )$
Dim toRecei8e As Intege,- i As Intege,
toRecei8e = !
2$ Second, we start a 0or /e7t loo+$
o, i = 1 4o 12
4$ e now check each number and only if the color of the number is red we add the number to
toeceie$
I3 Cells(i- 1).ont.Colo, = 8bRed 4en
toRecei8e = toRecei8e # Cells(i- 1).Value
*nd I3
;$ DonBt forget to close the loo+$
ext i
$ 0inally, we dis+lay the money still to receie$ e use the C o+erator to concatenate !oin# two
strings$ Although toeceie is not a string it works here$
6sg+ox "Still to ,ecei8e " 7 toRecei8e 7 " dolla,s"
($ Place your macro in a command button and test it$
-
7/24/2019 Logical Operator And
10/77
esult:
Delete Blank Cells
&elow we will look at a +rogram in Excel VBAthat deletes blank cells$
Situation:
1$ 0irst, we declare two ariables of ty+e Integer$ .ne named counter and one named i$ e
initiali3e the ariable counter with alue )$
Dim counte, As Intege,- i As Intege,
counte, = !
-
7/24/2019 Logical Operator And
11/77
2$ /e7t, we check for each cell whether it is em+ty or not !G' means not e "" 4en
Cells(counte, # 1- 2).Value = Cells(i- 1).Value
counte, = counte, # 1
*nd I3
ext i
esult so far:
4$ 0inally, we em+ty ange!"A1:A1)"#, co+y the alues of column & to column A, and em+ty
ange!"&1:&1)"#$
Range("A19A1!").Value = ""
Range("A19A1!").Value = Range("+19+1!").Value
Range("+19+1!") = ""
Loop through Dened Range
-
7/24/2019 Logical Operator And
12/77
&elow we will look at a +rogram that loops through a defined range$ 0or e7am+le, when we
want to s
-
7/24/2019 Logical Operator And
13/77
$ If you want to check each cell in a randomly selected range, sim+ly re+lace:
Set ,ng = Range("A19A")
with:
Set ,ng = Selection
($ /ow, for e7am+le select ange!"A1:A2"#$
esult when you click the command button on the sheet:
Loop through !ntire Column
&elow we will look at a +rogram in Excel VBAthat loops through the entire first columnand
colors all alues that are lower than a certain alue$
-
7/24/2019 Logical Operator And
14/77
Place a command button on your worksheet and add the following code lines:
1$ 0irst, declare a ariable called i of ty+e @ong$ e use a ariable of ty+e @ong here because
@ong ariables hae larger ca+acity than Integer ariables$
Dim i As :ong
2$ /e7t, add the code line which changes the font color of all the cells in column A to black$
Columns(1).ont.Colo, = 8b+lac;
4$ Add the loo+$
o, i = 1 4o Ro
-
7/24/2019 Logical Operator And
15/77
;$ /e7t, we color all alues that are lower than the alue entered into cell D2$ m+ty cells are
ignored$ Add the following code lines to the loo+$
I3 Cells(i- 1).Value 5 Range("D2").Value And ot Is*mt(Cells(i- 1).Value) 4en
Cells(i- 1).ont.Colo, = 8bRed
*nd I3
esult when you click the command button on the sheet !this may take a while#:
Do "ntil Loop
Although not used ery often on this site, you might find yourself in a situation where you want
to use the o !ntil Loopin Excel VBA$ -ode +laced between Do ntil and @oo+ will be
re+eated until the +art after Do ntil is true$
-
7/24/2019 Logical Operator And
16/77
Place a command buttonon your worksheet and add the following code lines:
Dim i As Intege,
i = 1
Do ?ntil i > Cells(i- 1).Value = 2!
i = i # 1
:oo
esult when you click the command button on the sheet:
7+lanation: until i is higher than (, 7cel %&A +laces the alue 2) into the cell at the
intersection of row i and column 1 and increments i by 1$ As a result, the alue 2) will be +laced
into column A si7 times !not seen because 7cel %&A sto+s when i e
-
7/24/2019 Logical Operator And
17/77
Place a command button on your worksheet and add the following code lines:
1$ 0irst, we declare two ariables of ty+e Integer$ .ne named i and one named $
Dim i As Intege,- @ As Intege,
2$ Second, we add two 0or /e7t loo+s$
o, i = 1 4o Ste 2
o, @ = 1 4o Ste 2
4$ /e7t, we add the line which changes the background color of the cells to light gray$
Cells(i- @).Inte,io,.Colo,Index = 1
/ote: instead of -olorInde7 number 1 !light gray#, you can use any -olorInde7 number$
;$ -lose the two 0or /e7t loo+s$
ext @
ext i
$ *est the +rogram$
esult so far$
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
18/77
0or e7am+le, for i = 1 and = 1, 7cel %&A colors -ells!1,1#, for i = 1 and = 4 ! Ste+2#, 7cel
%&A colors -ells!1,4#, for i = 1 and = , 7cel %&A colors -ells!1,#, for i = 4 !Ste+ 2# and =
1, 7cel %&A colors -ells!4,1#, etc$
($ e are almost there$ *he only thing we need to do, is color the cells which are offsetby 1 row
below and 1 column to the right of the cells already colored$ Add the following code line to the
loo+$
Cells(i- @).Bset(1- 1).Inte,io,.Colo,Index = 1
6$ *est the +rogram$
esult:
Sort $umbers
http://www.excel-easy.com/vba/examples/step-keyword.htmlhttp://www.excel-easy.com/vba/examples/offset.htmlhttp://www.excel-easy.com/vba/examples/step-keyword.htmlhttp://www.excel-easy.com/vba/examples/offset.html -
7/24/2019 Logical Operator And
19/77
&elow we will look at a +rogram in Excel VBAthat sorts numbers$
Situation:
Place a command button on your worksheet and add the following code lines:
1$ 0irst, we declare three ariables of ty+e Integer and one ange obect$
Dim i As Intege,- @ As Intege,- tem As Intege,- ,ng As Range
2$ e initiali3e the ange obect rng with the numbers in column A$ e use the -urrentegion
+ro+erty for this$ -urrentegion is useful when we donBt know the e7act boundaries of a range in
adance !we want this +rogram to work for ? numbers but also for ?) numbers#$
Set ,ng = Range("A1").Cu,,entRegion
4$ e start two 0or /e7t loo+s$
o, i = 1 4o ,ng.Count
o, @ = i # 1 4o ,ng.Count
7+lanation: rng$-ount e
-
7/24/2019 Logical Operator And
20/77
If the aboe statement is true, we swa+ the numbers$
0or e7am+le: for i = 1 and = 2, the numbers 2 and 1) are being com+ared$ *he aboe statement
is not true$ *hus, no need to swa+ the numbers$ 7cel %&A increments by 1 and re+eats the
code lines for i = 1 and = 4$ Fou can easily see that is larger than 2, so still no need to swa+
the numbers$ e get the same result for = ;, = and = ($ hen we arrie at = 6, the aboe
statement is true since 1 is smaller than 2$
$ eswa+the numbers$ e tem+orarily store one number to tem+, so that 7cel %&A can swa+
the numbers +ro+erly$ Add the following code lines in the If statement$
0s
-
7/24/2019 Logical Operator And
21/77
Randomly Sort Data
&elow we will look at a +rogram in Excel VBAthat randomly sorts data!in this e7am+le
randomly sorts names#$
Situation:
1$ 0irst, we declare four ariables$ .ne ariable of ty+e String we call *em+String, one ariable
of ty+e Integer we call *em+Integer, one ariable of ty+e Integer we call i, and one ariable of
ty+e Integer we call $
Dim temSt,ing As St,ing- temIntege, As Intege,- i As Intege,- @ As Intege,
-
7/24/2019 Logical Operator And
22/77
2$ e write random numbers to column & !one for each name#$ e use the worksheet function
and&etween for this$
o, i = 1 4o
Cells(i- 2).Value = o,;seetunction.Rand+et
-
7/24/2019 Logical Operator And
23/77
temIntege, = Cells(i- 2).Value
Cells(i- 2).Value = Cells(@- 2).Value
Cells(@- 2).Value = temIntege,
6$ DonBt forget to close the If statement$
*nd I3
5$ DonBt forget to close the two loo+s$
ext @
ext i
?$ *est the +rogram$
esult:
/ote: you can add a line which deletes the numbers in column &$ ItBs een nicer to +lace the
numbers of each name in an array, so no numbers are +laced on your worksheet$ Eoweer, forillustratie +ur+ose weBe chosen to +lace the alues on the sheet$
Remo%e Duplicates
&elow we will look at a +rogram in Excel VBAthat removes duplicates$
Situation:
In column A we hae 1) numbers$ e want to remoe the du+licates from these numbers and
+lace the uni
-
7/24/2019 Logical Operator And
24/77
1$ 0irst, we declare four ariables$ toAdd of ty+e &oolean, uni
-
7/24/2019 Logical Operator And
25/77
list, we need another 0or /e7t loo+$ Again: if the number we want to add is e
-
7/24/2019 Logical Operator And
26/77
Complex Calculations
*he kth
term, *k, of a certain mathematical series is defined by the following formula:
Tk=;2# ; # 1
E; # '
*he first term, *1, of the series is obtained by substituting k = 1 into the formula i$e$
T1=12# # 1
=1
andE # ' 2
T2= 2
2
# 12 # 1 = 1' ... and so on1 # ' 2
&elow we will look at a +rogram in Excel VBAthat calculatesany term *kand summation of
terms u+ to /$
7+lanation: the user has the o+tion to enter "All" or ".dd", to res+ectiely calculate the sum of
the first / terms of the series or the sum of only the odd terms u+ to /$
Place a command button on your worksheet and add the following code lines:
1$ 0irst, we declare four ariables of ty+e Integer and one ariable of ty+e String$
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
27/77
Dim i- te,m- - steSiFe As Intege,
Dim sum4e As St,ing
2$ Second, we initiali3e the ariables$
i = ! = Range("C2").Value
sum4e = Range("C").Value
4$ m+ty the fields$
Range("A9+1!!!").Value = ""
Range("C").Value = ""
;$ Determine ste+Si3e$
Select Case sum4e Case Is = "All"
steSiFe = 1
Case Is = "dd"
steSiFe = 2
Case *lse
6sg+ox "*nte, a 8alid ex,ession in cell C"
*nd
*nd Select
*i+: go through our Select -ase+rogram to learn more about the Select -ase structure$
$ Do the calculations$
o, te,m = 1 4o Ste steSiFe
Cells( # i- 1).Value = te,m
Cells( # i- 2).Value = (te,m G 2 # ( % te,m) # 1) H ((E % te,m) # ')
Range("C").Value = Range("C").Value # Cells( # i- 2).Value
i = i # 1
ext te,m
7+lanation: we use the Ste+ keyword to s+ecify the increment !1 for "All" and 2 for ".dd"# for
the counter ariable of the loo+$
esult:
http://www.excel-easy.com/vba/examples/select-case.htmlhttp://www.excel-easy.com/vba/examples/step-keyword.htmlhttp://www.excel-easy.com/vba/examples/select-case.htmlhttp://www.excel-easy.com/vba/examples/step-keyword.html -
7/24/2019 Logical Operator And
28/77
&napsack #roblem
&elow we will look at a +rogram in Excel VBAthat solvesa small instance of a knapsack
problem$
Definition: Lien a set of items, each with a weight and a alue, determine the items to include
in a collection so that the total alue is as large as +ossible and the total weight is less than a
gien limit$ It deries its name from the +roblem faced by someone who is constrained by afi7ed8si3e kna+sack and must fill it with the most useful items$
7am+le: items with weights, alues and limit as gien$
-
7/24/2019 Logical Operator And
29/77
In 7cel this +roblem looks as follows:
1$ 0irst, we declare fie ariables of ty+e Double with names limit, weight, alue, totaleight
and ma7imum%alue$
Dim limit As Double-
-
7/24/2019 Logical Operator And
30/77
;$ /e7t, we check each +ossible solution$ e can either include an item !1# or leae it out !)#$
e start 0or /e7t loo+s$ .ne for each item$
o, i = ! 4o 1
o, @ = ! 4o 1
o, ; = ! 4o 1 o, l = ! 4o 1
o, m = ! 4o 1
$ e calculate the weight and the alue of a +ossible solution$
maximumValue And
-
7/24/2019 Logical Operator And
31/77
-
7/24/2019 Logical Operator And
32/77
Situation:
Place a command button on your worksheet and add the following code lines:
1$ 0irst, we declare a ariable called fullname of ty+e String, a ariable called comma+osition of
ty+e Integer, and a ariable called i of ty+e Integer$
Dim 3ullname As St,ing- commaosition As Intege,- i As Intege,
*he +roblem we are dealing with is that we need to tell 7cel %&A where we want to se+arate
the string$ In case of Smith, ike the comma is at +osition ( while in case of illiams, Janet the
comma is at +osition ?$
2$ e use a loo+ to e7ecute the o+erations on each name entered in 7cel$ 0irst, we initiali3e the
ariable fullname$ /e7t, we use the Instr function to find the +osition of the comma$
o, i = 2 4o '
3ullname = Cells(i- 1).Value
commaosition = InSt,(3ullname- "-")
4$ 0inally, we want to write the +art after the comma to column & and the +art in front of the
comma to column -$ Fou can achiee this by adding the lines:
Cells(i- 2).Value = 6id(3ullname- commaosition # 2)
Cells(i- ).Value = :e3t(3ullname- commaosition & 1)
id!fullname, comma+osition 2# means we want the +art of fullname starting at character
Bcomma+osition 2B !this is e7actly the first name#$
@eft!fullname, comma+osition 8 1# means we want the +art of fullname starting at the beginning
until character Bcomma+osition8 1B !this is e7actly the last name#$
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
33/77
;$ DonBt forget to close the loo+$
ext i
$ Add si7 names se+arated by a comma and s+ace to ange!"A2:A6"#$
($ *est the +rogram$
esult:
Re%erse Strings
&elow we will look at a +rogram in Excel VBAthat can reverse strings$
Situation:
Place a command button on your worksheet and add the following code lines:
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
34/77
1$ 0irst, we declare four ariables$ .ne ariable called te7t of ty+e String, one ariable called
reersed*e7t also of ty+e String, one ariable called length of ty+e Integer, and one ariable
called i of ty+e Integer$
Dim text As St,ing- ,e8e,sed4ext As St,ing- lengt As Intege,- i As Intege,
2$ e initiali3e two ariables$ e use the In+ut&o7 function to get a te7t string from the user$ e
use the @en function in 7cel %&A to get the length of a string$
text = Inut+ox("*nte, te text ou
-
7/24/2019 Logical Operator And
35/77
6$ *est the +rogram$
esult:
Con%ert to #roper Case
&elow we will look at a +rogram in Excel VBAthat converts text to proper case$ *hat is, the
first letter in each word in u++ercase, and all other letters in lowercase$
Situation:
1$ 0irst, we declare two ange obects$ e call the ange obects rng and cell$
Dim ,ng As Range- cell As Range
2$ e initiali3e the ange obect rng with the selected range$
Set ,ng = Selection
-
7/24/2019 Logical Operator And
36/77
4$ e want to check each cell in a randomly selected range !this range can be of any si3e#$ In
7cel %&A, you can use the 0or ach /e7t loo+ for this$ Add the following code lines:
o, *ac cell In ,ng
ext cell
/ote: rng and cell are randomly chosen here, you can use any names$ emember to refer to these
names in the rest of your code$
;$ *o ignore a cell that contains a formula, add the following code line between 0or ach and
/e7t !only if cell$Eas0ormula is false we continue#$
I3 ot cell./aso,mula 4en
*nd I3
$ /e7t, we want to conert each word in this range to B+ro+er caseB$ Fou can use the worksheet
function Pro+er for this task$ Add the following code line in your if statement$
cell.Value = o,;seetunction.,oe,(cell.Value)
($ *est the +rogram$
esult:
Count 'ords
-
7/24/2019 Logical Operator And
37/77
&elow we will look at a +rogram in Excel VBAthat counts the number of "ordsin a selected
range$ .ne or more s+aces are assumed to se+arate words$
Situation:
1$ 0irst, we declare two ange obects and three ariables$ e call the ange obects rng and
cell$ .ne Integer ariable we call cellords, one Integer ariable we call totalords, and one
String ariable we call content$
Dim ,ng As Range- cell As Range
Dim cello,ds- totalo,ds As Intege,- content As St,ing
2$ e initiali3e the ange obect rng with the selected range and the two ariables of ty+e Integer
with alue )$
Set ,ng = Selection
cello,ds = !
totalo,ds = !
4$ e want to check each cell in a randomly selected range !this range can be of any si3e#$ In
7cel %&A, you can use the 0or ach /e7t loo+ for this$ Add the following code lines:
o, *ac cell In ,ng
ext cell
/ote: rng and cell are randomly chosen here, you can use any names$ emember to refer to these
names in the rest of your code$
;$ /e7t, we determine for each cell in this range how many words it contains$ *o ignore a cellthat contains a formula, add the following code line between 0or ach and /e7t !only if
cell$Eas0ormula is false we continue#$
I3 ot cell./aso,mula 4en
*nd I3
-
7/24/2019 Logical Operator And
38/77
$ 0irst, we write the content of the cell to the ariable content$ /e7t, we remoe the s+aces at
the beginning and the end !if there are any#$ In 7cel %&A, you can use the *rim function for
this$ 0or e7am+le, " e7cel ba" will be conerted to "e7cel ba"$ Add the following code lines in
your If statement$
content = cell.Valuecontent = 4,im(content)
/ote: the trim function in 7cel %&A does not remoe e7tra s+aces between words, but thatBs
.M in this e7am+le$
($ At this +oint, a cell can still be em+ty$ If the cell is em+ty, we assign the alue ) to the ariable
cellords$ If not, it contains at least one word and we assign the alue 1 to the ariable
cellords$ Add the following code lines in your If statement$
I3 content = "" 4en cello,ds = !
*lse
cello,ds = 1
*nd I3
A cell can contain more than one word of course$ *hatBs e7actly what we want to find out now$
As an e7am+le we take: "e7cel ba"$ If a cell contains at least one s+ace at this stage, it contains
at least one more word$ Fou can use the Instr function in 7cel %&A to look for a s+ace$
Instr!content, " "# finds the +osition of the first s+ace in content$
6$ e will make use of the Do hile @oo+structure$ -ode +laced between these words !at ste+
5, ? and 1)# will be re+eated as long as the +art after Do hile is true$ e want to re+eat these
ste+s as long as Instr!content, " "# ' ) is true !as long as content contains a s+ace and thus more
words#$ Add the Do hile @oo+ in your If statement$
Do ile InSt,(content- " ") > !
:oo
5$ /e7t, we take the +art of content starting at the +osition of the first s+ace$ e use the id
function for this$
content = 6id(content- InSt,(content- " "))
0or e7am+le: id!"e7cel ba", InStr!"e7cel ba", " "## will gie " ba"$
?$ e trim the string again$
http://www.excel-easy.com/vba/loop.html#do-while-loophttp://www.excel-easy.com/vba/string-manipulation.html#midhttp://www.excel-easy.com/vba/loop.html#do-while-loophttp://www.excel-easy.com/vba/string-manipulation.html#mid -
7/24/2019 Logical Operator And
39/77
content = 4,im(content)
esult: "ba"
1)$ e increment cellords by 1$
cello,ds = cello,ds # 1
*his Do hile @oo+ will be re+eated as long as content contains a s+ace and thus more words$ In
our e7am+le, we e7it the Do hile @oo+ since "ba" does not contain a s+ace anymoreK esult:
this cell contains 2 words$
11$ After haing checked one cell, we add cellords to the ariable totalords$ *his code line
should be +laced outside the Do hile @oo+ but in the If statement$
totalo,ds = totalo,ds # cello,ds
*he whole +rocess starts again for the ne7t cell until all cells hae been checked$
12$ 0inally, we dis+lay the alue of totalords using a msgbo7$ *his code line should be +laced
outside the 0or ach /e7t loo+$
6sg+ox totalo,ds 7 "
-
7/24/2019 Logical Operator And
40/77
*his e7am+le teaches you how to compare dates and timesin Excel VBA$ Dates and times are
stored as numbers in 7cel and count the number of days since January ), 1?))$ hat you see
de+ends on the number format$
1$ nter some numbers in column A$
2$ *hese numbers are dates$ *his is a +erfect way to enter some dates without worrying about the
Date format$ -hange the format to Date !ight click on the column A header, 0ormat -ells and
choose Date#$
esult:
/ote: Dates are in S 0ormat$ onths first, Days Second$ *his ty+e of format de+ends on your
windows regional settings$
Place a command button on your worksheet and add the following code lines:
4$ Declare the ariable i of ty+e Integer$
Dim i As Intege,
;$ Add a 0or /e7t loo+$
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
41/77
o, i = 1 4o
ext i
$ *he Date function returns the current date without the time$ Add the following code line to the
loo+, to highlight all the cells containing the current date !12N22N2)14#$
I3 Cells(i- 1).Value = Date 4en Cells(i- 1).ont.Colo, = 8bRed
esult:
($ Add the following code line to the loo+, to highlight all the dates earlier than );N1?N2)11$
I3 Cells(i- 1).Value 5 DateValue("A,il 1E- 2!11") 4en Cells(i- 1).ont.Colo, = 8bRed
esult:
6$ &ut what about times, we hear you say$ *hey are the decimals$ Switch back to Leneral format
and change the numbers to decimal numbers$
-
7/24/2019 Logical Operator And
42/77
5$ /ow change the format to BDate and *imeB format$
esult:
-
7/24/2019 Logical Operator And
43/77
?$ If you want to highlight all cells containing the current date, we cannot use the code line at
anymore$ hy notH &ecause the numbers in column A are decimal numbers now$ -om+aring it
with Date !a whole number# would not gie any match$ !It would only gie a match with
12N22N2)14 at midnight e7actlyK# *he following code line does work:
I3 Int(Cells(i- 1).Value) = Date 4en Cells(i- 1).ont.Colo, = 8bRed
7+lanation: we sim+ly use the Int function$ *he Int function rounds a number down to the
nearest integer$ *his way we can get the dates without the times and com+are these dates with
Date$
esult:
1)$ Add the following code line to highlight all the cells containing times in the morning$
I3 (Cells(i- 1).Value & Int(Cells(i- 1).Value)) 5 !. 4en Cells(i- 1).ont.Colo, = 8bRed
7+lanation: we only need the decimals so therefore we subtract the integer +art$ /oon !halfwaythrough the day# is re+resented as )$$ Decimals lower than )$ are the times in the morning$
esult:
-
7/24/2019 Logical Operator And
44/77
DateDi( Function
*he ateiff functionin Excel VBAcan be used to get the number of days between two dates$
Place a command buttonon your worksheet and add the following code lines:
Dim J,stDate As Date- secondDate As Date- n As Intege,
J,stDate = DateValue("Kun 1E- 2!1!")
secondDate = DateValue("Kul 2- 2!1!")
n = DateDiB("d"- J,stDate- secondDate)
6sg+ox n
7+lanation: first, we declare two dates$ /e7t, we initiali3e the two dates using the Date%alue
function$ *he DateDiff function has three arguments$ 0ill in "d" for the first argument since we
want the number of days between two dates$ 0inally, we use a sg&o7 to dis+lay the number of
days between the two dates$
esult when you click the command button on the sheet:
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
45/77
-hange "d" to "ww" to get the number of weeks between two dates$ Place your cursor on
DateDiff in the %isual &asic ditor and click 01 for hel+ on the other interal s+ecifiers$
'eekdays
&elow we will look at a +rogram in Excel VBAthat calculates the number of "eekdaysbetween
two dates$
eekdays are: onday, *uesday, ednesday, *hursday and 0riday$
Situation:
/ote: Dates are in S 0ormat$ onths first, Days Second$ *his ty+e of format de+ends on your
windows regional settings$
1$ 0irst, we declare fie ariables$ date1 of ty+e Date, date2 of ty+e Date, date*o-heck of ty+e
Date, days&etween of ty+e Integer, weekdays of ty+e Integer and i of ty+e Integer$
Dim date1 As Date- date2 As Date- date4oCec; As Date
Dim das+et
-
7/24/2019 Logical Operator And
46/77
2$ e initiali3e four ariables$ e use the DateDiff function to initiali3e the ariable
days&etween$ *his function has three arguments$ e fill in "d" for the first argument since we
want the number of days between date1 and date2$
-
7/24/2019 Logical Operator And
47/77
esult:
Delay a )acro
*o e7ecute a sub in Excel VBAafter a specific time, use on*ime, /ow and the *ime%alue
function$ 0irst, +lace a sub into a module$
1$ .+en the %isual &asic ditorand click Insert, odule$
2$ Add the following sub with name reminder:
Sub ,eminde,()
6sg+ox "Don0t 3o,get ou, meeting at 1$.!"
*nd Sub
e want 7cel %&A to e7ecute this sub seconds after a command button is clicked$
2$ Place a command button on your worksheet and add the following code line:
Alication.n4ime o
-
7/24/2019 Logical Operator And
48/77
;$ If you want to e7ecute this sub at a s+ecific time, sim+ly use the following code line:
Alication.n4ime 4imeValue("1$9!!9!! am")- ",eminde,"
$ -lick the command button on the worksheet and wait until 1;:)) A to see your sub being
e7ecuted$
/ote: you will +robably not use 7cel %&A to remind yourself of an im+ortant meeting, but if
you do want, itBs best to +ut a macro like this in a orkbook .+en ent$ &y doing this, you will
automatically receie a reminder at 1;:)) A !you donBt hae to click a command button to
actiate the macro#$ .f course, you will only receie the reminder when you leae your
workbook o+en$
*ear +ccurrences
&elow we will look at a +rogram in Excel VBAthat counts the number of year occurrences$
Situation:
http://www.excel-easy.com/vba/events.html#workbook-open-eventhttp://www.excel-easy.com/vba/events.html#workbook-open-event -
7/24/2019 Logical Operator And
49/77
/ote: Dates are in S 0ormat$ onths first, Days second$ *his ty+e of format de+ends on your
windows regional settings$
1$ 0irst, we declare three ariables of ty+e Integer$ .ne ariable we call year-ount, one ariable
we call yearAsk, and one ariable we call i$
Dim ea,Count As Intege,- ea,As; As Intege,- i As Intege,
2$ e initiali3e year-ount with the alue ) and yearAsk with the alue of cell -;$
ea,Count = !
ea,As; = Range("C$").Value
4$ e start a 0or /e7t loo+$
o, i = 1 4o 1
;$ e now check each date and only if the year of the date e
-
7/24/2019 Logical Operator And
50/77
ext i
($ 0inally, we dis+lay the total year occurrences$ e use the C o+erator to concatenate !oin# two
strings$
6sg+ox ea,Count 7 " occu,,ences in ea, " 7 ea,As;
6$ Place your macro in a command button and test it$
esult:
/ote: because we made yearAsk ariable, you can sim+ly count the number of year occurrences
of another year by entering another year in cell -;, and clicking on the command button again$
Tasks on Schedule
&elow we will look at a +rogram in Excel VBA that sets the background color of tasks that are
on scheduleto green, and sets the background color of tasks that are behind schedule to red$
Situation:
.n Sheet1 we hae three tasks !O, F, #$ A "1" indicates that a task has been com+leted$ A task is
on schedule if a "1" e7ist in eery column u+ to and including todayBs date$ *oday itBs (8un$
*asks O and F are on schedule$ *ask is behind schedule !no "1" in cell 5#$
-
7/24/2019 Logical Operator And
51/77
-reate a orksheet -hange ent$ -ode added to the orksheet -hange ent will be e7ecuted
by 7cel %&A when you change a cell on a worksheet$
1$ .+en the %isual &asic ditor$
2$ Double click on Sheet1 !Sheet1# in the Proect 7+lorer$
4$ -hoose orksheet from the left dro+8down list$ -hoose -hange from the right dro+8down list$
Add the following code lines to the orksheet -hange ent:
;$ Declare two ariables of ty+e Integer$
Dim i As Intege,- @ As Intege,
http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
52/77
$ Add a Do hile @oo+$
Do ile Cells( # i- 1).Value 5> ""
i = i # 1:oo
7+lanation: 0or i = ), 7cel %&A checks task O, for i = 1, task F, etc$ 7cel %&A leaes the Do
hile loo+ when -ells!( i, 1#$%alue is em+ty !no more tasks to check#$
Add the following code lines !at (, 6 and 5# to the Do hile @oo+$
($ Initiali3e the ariable with alue )$
@ = !
6$ Set the background color of a task to green assuming that a task is on schedule !this is not
necessarily true of course#$
Cells( # i- 1).Inte,io,.Colo,Index = $
5$ Add another Do hile @oo+$
Do ile Cells($- 2 # @).Value 5= Date
I3 Cells( # i- 2 # @).Value = ! 4en Cells( # i- 1).Inte,io,.Colo,Index =
@ = @ # 1
:oo
/ote: the Date function returns todayBs date$
7+lanation: 0or i = ), = ), 7cel %&A checks cell &($ 0or i = ), = 1, 7cel %&A checks cell
-(, etc$ A task is on schedule if a "1" e7ists in eery column u+ to and including todayBs date$ If
7cel %&A finds a ")", it sets the background color of the task to red$
?$ *est the +rogram$ 0or e7am+le, indicate that task on (8un has been com+leted$ As a result,
task will automatically turn green$
http://www.excel-easy.com/vba/loop.html#do-while-loophttp://www.excel-easy.com/vba/loop.html#do-while-loop -
7/24/2019 Logical Operator And
53/77
Sort Birthdays
&elow we will look at a +rogram in Excel VBAthat sorts birthdaysto months first and days
second !so we ignore years#$ e want the birthday with the lowest month number at the first
+osition$ If there are birthdays with e
-
7/24/2019 Logical Operator And
54/77
/ote: Dates are in S 0ormat$ onths first, Days second$ *his ty+e of format de+ends on your
windows regional settings$
1$ 0irst, we declare eight ariables$ .ne Date ariable we call tem+Date, one String ariable we
call tem+/ame$ *he other si7 ariables are Integer ariables with names month*o-heck,
day*o-heck, month/e7t, day/e7t, i and $
Dim temDate As Date- temame As St,ing
Dim mont4oCec; As Intege,- da4oCec; As Intege,- montext As Intege,-daext As Intege,- i As Intege,- @ As Intege,
2$ e start two 0or /e7t loo+s$
o, i = 2 4o 1
o, @ = i # 1 4o 1
7am+le: for i = 2, = 4, ;, $$$ , 12 and 14 are checked$
4$ e initiali3e four Integer ariables$ e use the onth function to get the month of a date and
the Day function to get the day of a date$
mont4oCec; = mont(Cells(i- 2).Value)
da4oCec; = da(Cells(i- 2).Value)
montext = mont(Cells(@- 2).Value)
daext = da(Cells(@- 2).Value)
-
7/24/2019 Logical Operator And
55/77
0or e7am+le: at the start, for i = 2Q the date of ®e, and = i 1 = 2 1 = 4Q the date of /iels
will be chosen$
;$ *o sort the dates +ro+erly, we com+are the first date !month*o-heck and day*o-heck# with
the ne7t date !month/e7t and day/e7t#$ If the ne7t date is BlowerB, we swa+ the dates and names$
Add the following If *hen statement$
I3 (montext 5 mont4oCec;) , (montext = mont4oCec; And daext 5
da4oCec;) 4en
*nd I3
If the aboe statement is true, we swa+ the dates and names$
0or e7am+le: for i = 2 and = 4, the date of ®e and /iels are checked$ onth/e7t = (,
month*o-heck = 2$ *he aboe statement is not true since month/e7t is higher thanmonth*o-heck$ 7cel %&A increments by 1 and re+eats the code lines for i = 2 and = ;$ Fou
can easily see that Joost ! = ;# has a higher month number than ®e, so we go to the ne7t one$
e get the same result for = and = ($ hen we arrie at = 6, we hae the following
ariables: month/e7t = 2 and day/e7t = ?$ onth*o-heck = 2 and day*o-heck = 12$ /ow the
aboe statement is true since month/e7t = month*o-heck and day/e7t !?# is lower than
day*o-heck !12#$
$ eswa+the dates$ e tem+orarily store one date to tem+Date, so that 7cel %&A can swa+
the dates +ro+erly$ Add the following code lines in the If statement$
0s
-
7/24/2019 Logical Operator And
56/77
day*o-heck at the start of our ne7t iteration !for i = 2 and = 5#$ e will now com+are ichard
with Dineke ! = 5#$ Fou can easily see that there is no need to re+lace those dates and names
because ichard has a BlowerB date$ As a matter of fact, there is no need to re+lace ichard !i = 2#
with Jan ! = ?#, endy ! = 1)#, Jeroen ! = 11#, John ! = 12# and Debby ! = 14#$ *hat is
because ichard has the BlowestB date$ *his way 7cel %&A will get !for i = 2# the BlowestB date at
the first +osition$ *o get the second BlowestB date at the second +osition, 7cel %&A re+eats the
e7act same ste+s for i = 4$ *o get the third BlowestB date at the third +osition, 7cel %&A re+eats
the e7act same ste+s for i = ;, etc$
5$ -lose the first 0or /e7t loo+ !.utside the If statement#$
ext i
?$ *est your +rogram$
esult:
Be,oreDoubleClick !%ent
-
7/24/2019 Logical Operator And
57/77
-ode added to the orksheet Beforeouble#lick Eventwill be e7ecuted by Excel VBAwhen
you double click a cell on a worksheet$
1$ .+en the %isual &asic ditor$
2$ Double click on a sheet !for e7am+le Sheet1# in the Proect 7+lorer$
4$ -hoose orksheet from the left dro+8down list$ -hoose &eforeDouble-lick from the right
dro+8down list$
/ote: the BRB symbol is used to continue the statement on a new line !in order to show you the
com+lete code#$
Add the following code lines to the orksheet &eforeDouble-lick ent:
;$ *he code line below colors the actie cell red$
4a,get.ont.Colo, = 8bRed
$ Set the -ancel argument to true if you donBt want the default double click action !cell edit
mode# to occur$
Cancel = 4,ue
($ *est the +rogram by double clicking a cell on Sheet1$
esult:
http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
58/77
Highlight -cti%e Cell
&elow we will look at a +rogram in Excel VBAthat highlights the ro" and column of the
Active #ell!selected cell#$ *his +rogram will ama3e and im+ress your boss$
Situation:
-
7/24/2019 Logical Operator And
59/77
ach time we change the Actie -ell on Sheet1, a macro needs to be e7ecuted$ Fou can achiee
this by creating a orksheet Selection-hange ent$
1$ .+en the %isual &asic ditor$
2$ Double click on Sheet1 !Sheet1# in the Proect 7+lorer$
4$ -hoose orksheet from the left dro+8down list$ -hoose Selection-hange from the right dro+8
down list$
http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
60/77
Add the following code lines to the orksheet Selection-hange ent:
;$ e declare four ariables of ty+e Integer$ .ne named row/umber%alue, one named
column/umber%alue, one named i and one named $
Dim ,o
-
7/24/2019 Logical Operator And
61/77
Create a Footer Be,ore #rinting
&elow we will look at a +rogram in Excel VBAthat creates a footer before printingaworkbook$
-reate a orkbook &eforePrint ent$ -ode added to the orkbook &eforePrint ent will be
e7ecuted by 7cel %&A before you +rint a workbook$
1$ .+en the %isual &asic ditor$
2$ Double click on *his orkbook in the Proect 7+lorer$
4$ -hoose orkbook from the left dro+8down list$ -hoose &eforePrint from the right dro+8downlist$
;$ *o create a footer, add the following code line to the orkbook &eforePrint ent:
Acti8eSeet.ageSetu.:e3toote, = Acti8eo,;boo;.ullame
/ote: *he PageSetu+ obect contains all +age setu+ attributes !left footer, bottom margin, +a+er
si3e, left margin, and so on# as +ro+erties$
$ *est the +rogram by +rinting your workbook$
esult:
http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
62/77
Bills and Coins
&elow we will look at a +rogram in Excel VBAthat s+lits an amount of money into bills and
coins$
Situation:
-reate a orksheet -hange ent$ -ode added to the orksheet -hange ent will be e7ecuted
by 7cel %&A when you change a cell on a worksheet$
1$ .+en the %isual &asic ditor$
http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
63/77
2$ Double click on Sheet1 !Sheet1# in the Proect 7+lorer$
4$ -hoose orksheet from the left dro+8down list$ -hoose -hange from the right dro+8down list$
Add the following code lines to the orksheet -hange ent:
;$ Declare a ariable called amount of ty+e Double and a ariable i of ty+e Integer$
Dim amount As Double- i As Intege,
$ *he orksheet -hange ent listens to all changes on Sheet1$ e only want 7cel %&A to dosomething if something changes in cell &2$ *o achiee this, add the following code line:
I3 4a,get.Add,ess = "L+L2" 4en
($ e initiali3e the ariable amount with the alue of cell &2$
amount = Range("+2").Value
6$ e em+ty the range with the fre
-
7/24/2019 Logical Operator And
64/77
?$ e will make use of the Do hile @oo+structure$ -ode +laced between these words will be
re+eated as long as the +art after Do hile is true$ e want 7cel %&A to re+eat the code lines
at ste+ 1) as long as amount is larger or e= Cells(i- 1).Value
:oo
1)$ Add the following code lines to the Do hile @oo+$
Cells(i- 2).Value = Cells(i- 2).Value # 1
amount = amount & Cells(i- 1).Value
7+lanation: as long as amount is larger or e
-
7/24/2019 Logical Operator And
65/77
/ote: of course the entered amount does not necessarily contains eery billNcoin$ If amount does
not contain a certain billNcoin, the +art after Do hile neer becomes true for this billNcoin and
7cel %&A goes directly to the ne7t billNcoin$
Rolling -%erage Table
&elow we will look at a +rogram in Excel VBAthat creates a rolling average table$ Place a
command buttonon your worksheet and add the the following code line:
Range("+").Value = o,;seetunction.Rand+et
-
7/24/2019 Logical Operator And
66/77
-reate a orksheet -hange ent$ -ode added to the orksheet -hange ent will be e7ecuted
by 7cel %&A when you change a cell on a worksheet$
1$ .+en the %isual &asic ditor$
2$ Double click on Sheet1 !Sheet1# in the Proect 7+lorer$
4$ -hoose orksheet from the left dro+8down list$ -hoose -hange from the right dro+8down list$
http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
67/77
Add the following code lines to the orksheet -hange ent:
;$ Declare a ariable called newalue of ty+e Integer and two ranges !firstfouralues and
lastfouralues#$
Dim ne
-
7/24/2019 Logical Operator And
68/77
?$ 0inally, enter the formula =A%AL!D4:D6# into cell D5$
1)$ *est the +rogram by clicking on the command button$
Dynamic -rray
If the si3e of your array increases and you donBt want to fi7 the si3e of the array, you can use the
$eim key"ord$ Excel VBAthen changes the si3e of the array automatically$
Add some numbers to column A$
Place a command button on your worksheet and add the following code lines:
1$ 0irst, we declare the array named numbers$ Also declare two ariables of ty+e Integer$ .ne
named si3e and one named i$
Dim numbe,s() As Intege,- siFe As Intege,- i As Intege,
/ote: the array has no si3e yet$ numbers, si3e and i are randomly chosen here, you can use any
names$ emember to refer to these names in the rest of your code$
2$ /e7t, we determine the si3e of the array and store it into the ariable si3e$ Fou can use the
worksheet function -ountA for this$ Add the following code line:
siFe = o,;seetunction.CountA(o,;seets(1).Columns(1))
4$ e now know the si3e of the array and we can redimension it$ Add the following code line:
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
69/77
ReDim numbe,s(siFe)
;$ /e7t, we initiali3e each element of the array$ e use a loo+$
o, i = 1 4o siFe
numbe,s(i) = Cells(i- 1).Valueext i
$ e dis+lay the last element of the array using a sg&o7$
6sg+ox numbe,s(siFe)
($ 7it the %isual &asic ditor and click the command button on the sheet$
esult:
6$ /ow to clearly see why this is called a dynamic array, add a number to column A$
5$ -lick the command button again$
-
7/24/2019 Logical Operator And
70/77
-onclusion: 7cel %&A has automatically changed the si3e of this dynamic array$
?$ hen you use the eDim keyword, you erase any e7isting data currently stored in the array$
0or e7am+le, add the following code lines to the +reiously created code:
ReDim numbe,s()
6sg+ox numbe,s(1)
esult:
*he array is em+ty$
1)$ hen you want to +resere the data in the e7isting array when you redimension it, use the
Presere keyword$
ReDim ,ese,8e numbe,s()
6sg+ox numbe,s(1)
esult:
-
7/24/2019 Logical Operator And
71/77
-rray Function
*he Array functionin Excel VBAcan be used to
-
7/24/2019 Logical Operator And
72/77
;$ Add .+tion &ase 1 to the Leneral Declarations section if you want the inde7 to start from 1$
esult when you click the command button again$
0or a +ractical e7am+le of the Array function, see our e7am+le +rogramonth /ames
)onth $ames
&elow we will look at a +rogram in Excel VBAwhich creates a !ser efined %unctionthat
uses the Array function to return the names of the months$
ser defined functions need to be +laced into a module$
1$ .+en the %isual &asic ditorand click Insert, odule$
2$ Add the following code line:
http://www.excel-easy.com/vba/examples/month-names.htmlhttp://www.excel-easy.com/vba/examples/user-defined-function.htmlhttp://www.excel-easy.com/vba/examples/user-defined-function.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/examples/month-names.htmlhttp://www.excel-easy.com/vba/examples/user-defined-function.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
73/77
unction 64/A6*S()
*he name of our 0unction is ./*E/AS$ *he em+ty +art between the brackets means we
gie 7cel %&A nothing as in+ut$
4$ *he Array function allows us to assign alues to a %ariant array in one line of code$
64/A6*S = A,,a("Kan"- "eb"- "6a,"- "A,"- "6a"- "Kun"- "Kul"- "Aug"- "Se"-
"ct"- "o8"- "Dec")
;$ DonBt forget to end the function$
*nd unction
$ /ow you can use this function, ust like any other 7cel function, to return the names of the
months$ Select twele hori3ontal cells, enter the function =./*E/AS!# and +ress -*@
SEI0* /*$
esult:
/ote: you cannot delete a single month$ *o delete the months, select the range A1:@1 and +ress
Delete$ *his function is only aailable in this workbook$
Si.e o, an -rray
*o get the si&e of an arrayin Excel VBA, you can use the &ound and @&ound functions$
Place a command buttonon your worksheet and add the following code lines:
1$ 0irst, we need to declare the array$ .ur array has two dimensions$ It consists of rows and 2
columns$ Also declare two ariables of ty+e Integer$
http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button -
7/24/2019 Logical Operator And
74/77
Dim ilms(1 4o - 1 4o 2) As St,ing- x As Intege,- As Intege,
*he array may look like this$
2$ /e7t, we get the si3e of the array$ Add the following code lines:
x = ?+ound(ilms- 1) & :+ound(ilms- 1) # 1 = ?+ound(ilms- 2) & :+ound(ilms- 2) # 1
&ound!0ilms, 1# gies the u++er limit of the first dimension, which is $
@&ound!0ilms, 1# gies the lower limit of the first dimension, which is 1$
&ound!0ilms, 2# gies the u++er limit of the second dimension, which is 2$
@&ound!0ilms, 2# gies the lower limit of the second dimension, which is 1$
As a result, 7 e
-
7/24/2019 Logical Operator And
75/77
"ser Dened Function
&elow we will look at a +rogram in Excel VBAthat creates a !ser efined %unction$ 7cel hasa large collection of functions$ In most situations those functions are sufficient to get the ob
done$ If not, you can create your own function called ser Defined 0unction or custom Excel
function$ Fou can access a ser Defined 0unction ust like any other 7cel function$
e want to create a function called S%//&S that finds the sum of the een
numbers of a randomly selected range$
Situation:
ser defined functions need to be +laced into a module$
1$ .+en the %isual &asic ditorand click Insert, odule$
2$ Add the following code line:
unction S?6*V*?6+*RS(,ng As Range)
*he name of our 0unction is S%//&S$ *he +art between the brackets means we
gie 7cel %&A a range as in+ut$ e name our range rng, but you can use any name$
4$ /e7t, we declare a ange obect and call it cell$
Dim cell As Range
;$ e want to check each cell in a randomly selected range !this range can be of any si3e#$ In
7cel %&A, you can use the 0or ach /e7t loo+ for this$ Add the following code lines:
http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor -
7/24/2019 Logical Operator And
76/77
o, *ac cell In ,ng
ext cell
/ote: cell is randomly chosen here, you can use any name$
$ /e7t, we check for each alue in this range whether it is een or not$ e use the od o+erator
for this$ *he od o+erator gies the remainder of a diision$ So 6 mod 2 would gie 1$ 6 is
diided by 2 !4 times# to gie a remainder of 1$ Eaing said this, it is easy to check whether a
number is een or not$ .nly if the remainder of a number diided by 2 is ), the number is een$ 5
mod 2 gies ), 5 is diided by 2 e7actly ; times, and therefore 5 is een$ Add the following If
statement to the 0or ach /e7t loo+$
I3 cell.Value 6od 2 = ! 4en
*nd I3
($ .nly if this statement is true, we add the alue to S%//&S$ Add the following
code line in the If statement$
S?6*V*?6+*RS = S?6*V*?6+*RS # cell.Value
6$ DonBt forget to end the function !outside the loo+#$
*nd unction
5$ /ow you can use this function, ust like any other 7cel function, to find the sum of the een
numbers of a randomly selected range$
esult:
ell doneK *hatBs how easy ser Defined 0unctions in 7cel %&A are$ /ote: this function is
only aailable in this workbook$
-
7/24/2019 Logical Operator And
77/77