SlideShare a Scribd company logo
1 of 53
Download to read offline
LECTURE 5

More loops
1D Arrays
SUMMARY
Looping userform controls
Generalising loops
Nested For-Next loops
1D Arrays
MORE FOR-NEXT LOOPS

Loop Controls
LOOPING USERFORM CONTROLS
Labels 1,
2 and 3

Public Sub Command_LoopControls_Click()

Label1.Caption = Cells(2, 2).Value
Label2.Caption = Cells(2, 3).Value
Label3.Caption = Cells(2, 4).Value
End Sub
These values are changing
LOOPING USERFORM CONTROLS
Public Sub Command_LoopControls_Click()
i=1

i=2
i=3

Label1.Caption = Cells(2, 2).Value
Label2.Caption = Cells(2, 3).Value
Label3.Caption = Cells(2, 4).Value

End Sub
The label is i

The column
is i + 1
LOOPING USERFORM CONTROLS

The (Name) of the
userform control
LOOPING USERFORM CONTROLS

Use concatenation
LOOPING USERFORM CONTROLS

Use the ith label
LOOPING USERFORM CONTROLS

The column
is i + 1
EXERCISE 1. WRITE A FOR LOOP
Download Lecture 5 Student Example.xlsm
Write a For-Loop for this code in UserForm1.
 Remember to declare your counter!
Public Sub LoopExercise1_Click()

Range(“Investment”).Columns(1).Value = TextBox1.Value
Range(“Investment”).Columns(2).Value = TextBox2.Value
Range(“Investment”).Columns(3).Value = TextBox3.Value
End Sub

Questions:
 Are the cells being assigned the value of the textboxes?
 Or are the textboxes being assigned the values of the cells?
NESTED
FOR-NEXT LOOPS
NESTED FOR-NEXT LOOP
Repeat this twice

For i = 1 to 3
Cells(i, 1).Value = i
Next i

?
NESTED FOR-NEXT LOOP
Repeat this twice

For k = 1 to 2

For i = 1 to 3
Cells(i, 1).Value = i
Next i

Next k
NESTED FOR-NEXT LOOP
Repeat this twice

For i = 1 to 3
Cells(i, 1).Value = i
Next i

For k = 1 to 2
For i = 1 to 3
Cells(i, 1).Value = i
Next i
Next k
NESTED FOR-NEXT LOOP
Repeat this twice

For i = 1 to 3
Cells(i, 1).Value = i
Next i

For k = 1 to 2
For i = 1 to 3
Cells(i, k).Value = i
Next i
Next k
EXERCISE 2. NESTED FOR-NEXT LOOP
Use Lecture 5 Student Example.xlsm
 LoopExercise2 in Module1

Write a nested For-Loop for this output.
 Remember to declare your counter.

Repeat this twice
EXERCISE 2. SOLUTIONS
Cells(1, 1).Value = 1
Cells(1, 2).Value = 2
Cells(1, 3).Value = 3
Cells(2, 1).Value = 1
Cells(2, 2).Value = 2
Cells(2, 3).Value = 3

For i = 1 to 3
Cells(1, i).Value = i
Next i
Repeat this twice
EXERCISE 2. SOLUTIONS
Cells(1, 1).Value = 1
Cells(1, 2).Value = 2
Cells(1, 3).Value = 3
Cells(2, 1).Value = 1
Cells(2, 2).Value = 2
Cells(2, 3).Value = 3

For k = 1 to 2
For i = 1 to 3
Cells(1, i).Value = i
Next i
Next k
EXERCISE 2. SOLUTIONS
Cells(1, 1).Value = 1
Cells(1, 2).Value = 2
Cells(1, 3).Value = 3
Cells(2, 1).Value = 1
Cells(2, 2).Value = 2
Cells(2, 3).Value = 3

For k = 1 to 2
For i = 1 to 3
Cells(k, i).Value = i
Next i
Next k
EXERCISE 3. NESTED FOR-NEXT LOOPS
Use Lecture 5 Student Example.xlsm
 LoopExercise3 in Module1

Write a nested For-Loop for this output.
 Remember to declare your counter.

Repeat this three times
GENERALISING CODE

Using
variables
or
constants
instead of
explicit
numbers
WHAT DOES IT MEAN TO GENERALISE?
Dim i As Integer

For i = 1 to 10
Cells(i +1, 1).Value = i
Next i
I know the number
Dim i As Integer

of TIMEPERIODS
in advance

Const TIMEPERIODS = 10
For i = 1 to TIMEPERIODS
Cells(i +1, 1).Value = i
Next i
WHAT DOES IT MEAN TO GENERALISE?
Unknown until the user runs the program

Dim i As Integer
Dim nStocksSelected As Integer

For i = 1 to nStocksSelected
[…..]
Next i
I only want this code to run for the
number of stocks selected by the user
WHAT DOES IT MEAN TO GENERALISE?
Replace specific numbers with variables
 And assign those variables a value

Enables code to be changed/updated quickly
 Only have to change one value instead of every value

Enables you to use user inputs in your loops
 You don’t know these in advance
1D ARRAYS
ARRAYS
Hold a range (or set) of values
Basically a set of variables
Your arrays will mainly be 1 or 2 dimensions

arrayName(5)

arrayName(5)

arrayName(5, 4)

arrayName is the name of your array
ARRAYS
Hold a range (or is onlyvalues 1D Arrays
set) of about
Today
Basically a set of variables
Your arrays will mainly be 1 or 2 dimensions

arrayName(5)

arrayName(5)

arrayName(5, 4)

arrayName is the name of your array
DECLARING ARRAYS
The same rules apply to arrays as to variables
 Disposable, local or global? – Declare in the right place
 Must specify a data type

Also, need to specify the size of the array
 The “size” is the number of elements in the array

Public Sub DescriptiveStats()

5 stock prices

Dim stockPrices(5) As Double
Dim stockRet(4) As Double
End Sub

4 stock returns
DECLARING ARRAYS

5 stock prices
4 stock returns
The same rules apply to arrays as to variables
 Disposable, local or global? – Declare in the right place
 Must specify a data type

Also, need to specify the size of the array
 The “size” is the number of elements in the array

Public Sub DescriptiveStats()

5 stock prices

Dim stockPrices(5) As Double
Dim stockRet(4) As Double
End Sub

4 stock returns
DECLARING ARRAYS
Many times we don’t know the number of
elements that will be in the array.
So, first declare them empty (disposable, local or
global): Dim stockPrices() As Double
For example,
Dim stockRet() As Double

these are local

Public Sub DescriptiveStats()
End Sub

General format
for declaration

arrayName() As DataType
arrayName:= the name of the array
DataType:= Integer, Double, String…
DECLARING ARRAYS
After the size of the array is know, re-declare it
inside a procedure
Dim stockPrices() As Double
Dim stockRet() As Double
Dim nDays As Integer
Public Sub DescriptiveStats()

nDays = Combobox1.value
ReDim stockPrices(nDays) As Double
ReDim stockRet(nDays-1) As Double

End Sub

Arrays will most likely
need to be local or
global

User selects number
of days from a
ComboBox on the
userform
Redim both arrays
using the variable
DECLARING ARRAYS
After the size of the array is know, re-declare it
inside a procedure

General format for
re-declaration
ReDim arrayName(n) As DataType
n:= the number of elements in the array
ARRAYS
VBA counts elements of arrays starting with 0
For example,
 This array is named StockPrices
 It has 5 elements (i.e., 5 stock prices)

Count
0
1

StockPrices(1)

2
3

StockPrices(2)
StockPrices(3)

4

StockPrices(4)

StockPrices(0)
ARRAYS
To force VBA to count from 1
 Use Option Base 1 at the top of each module

Count
1
2

StockPrices(2)

3
4

StockPrices(3)
StockPrices(4)

5

StockPrices(5)

StockPrices(1)
BEFORE ARRAYS…
We had to declare multiple variables like this:

And assign values like this:
WITH ARRAYS…
We can declare an array like this:

And assign values like this:
FILLING ARRAYS FROM CELLS OR RANGES

A 1D array and a
single For-Next
loop so this is only
for Stock 1

i=1
i=2
i=3
i=4
i=5
.
.
.
i=9
FILLING ARRAYS FROM CELLS OR RANGES

Cells(1,1)

i=1
i=2
i=3
i=4
i=5
.
.
.
i=9

A 1D array and a
single For-Next
loop so this is only
for Stock 1

Range Named
“Prices”
FILLING ARRAYS IN GENERAL
You can ‘fill’ arrays with values from…
 Cells
 Ranges
 Userform controls
 Other variables or arrays
 Using equations (e.g., calculate returns)
OUTPUTTING ARRAYS TO CELLS OR RANGES

i=1

i=2

i=3

i=4

i=5

**This is assuming we have assigned each element of the array weights() a value**
OUTPUTTING ARRAYS TO CELLS OR RANGES

Range Named
“StockWeights”

Cells(1,1)

i=1

i=2

i=3

i=4

i=5

**This is assuming we have assigned each element of the array weights() a value**
OUTPUTTING ARRAYS IN GENERAL
You can ‘output’ the value of arrays to…
 Cells
 Ranges
 Userform controls
 Other variables or arrays
EXERCISE 4A. WRITE A FOR LOOP
Use Lecture 5 Student Example.xlsm
 LoopExercise4A in Module1

Declare an array for stock returns
Use that array in a For-Loop to rewrite this code.
 Remember to declare your counter!
Public Sub LoopExercise4A()
stockRet1 = Cells(4, 6).Value
stockRet2 = Cells(5, 6).Value
stockRet3 = Cells(6, 6).Value
End Sub
EXERCISE 4B. WRITE A FOR LOOP
Now, instead of using cell references use range
references to assign the array values:
Public Sub LoopExercise4A()
stockRet1 = Cells(4, 6).Value
stockRet2 = Cells(5, 6).Value
stockRet3 = Cells(6, 6).Value
End Sub

Public Sub LoopExercise4B()
stockRet1 = Range(“Returns”).Cells(1, 1)
stockRet2 = Range(“Returns”).Cells(2, 1)
stockRet3 = Range(“Returns”).Cells(3, 1)
End Sub

Exercise 4A

Exercise 4B

Check your array has correct values by either:
 Outputting the array values to different cells (any cells)
 Or by using a message box
 Or by stepping through your code and checking the value
of each array element.
WRITE SUMS USING LOOPS & ARRAYS
sum = stockPrice(1) + stockPrice(2) + stockPrice(3)
WRITE SUMS USING LOOPS & ARRAYS
sum = stockPrice(1) + stockPrice(2) + stockPrice(3)

i=1

i = 1 sum = stockPrice(1)
WRITE SUMS USING LOOPS & ARRAYS
sum = stockPrice(1) + stockPrice(2) + stockPrice(3)

i=1

i=2

i = 1 sum = stockPrice(1)
i = 2 sum = sum + stockPrice(2)
WRITE SUMS USING LOOPS & ARRAYS
sum = stockPrice(1) + stockPrice(2) + stockPrice(3)

i=1

i=2

i=3

i = 1 sum = stockPrice(1)
i = 2 sum = sum + stockPrice(2)
i = 3 sum = sum + stockPrice(3)
WRITE SUMS USING LOOPS & ARRAYS
sum = stockPrice(1) + stockPrice(2) + stockPrice(3)

i=1

i=2

i=3

sum = 0
i = 1 sum = sum + stockPrice(1)
i = 2 sum = sum + stockPrice(2)
i = 3 sum = sum + stockPrice(3)
WRITE SUMS USING LOOPS & ARRAYS
sum = stockPrice(1) + stockPrice(2) + stockPrice(3)
Make sure the
sum starts at 0
EXERCISE 5. WRITE A FOR LOOP
Use Lecture 5 Student Example.xlsm
 LoopExercise4B in Module1

Find the sum of the 3 stock returns you assigned to
an array in Exercise 4B using a For-Next loop.
Check your sum with a message box. If you get the
following result, you are correct:
LEARNING OUTCOMES
 You are ready to move on when:
 LO21: You can use loops and concatenation to assign values to
controls on a userform or assign cells, ranges or 1D arrays
values from userform controls.
 LO22: You can describe what it means to generalise code. You
can also determine when loops should be generalised and how
to do so within your code.
 LO23: You can define what a nested loop is. You can also
construct basic nested loops to output values to cells or ranges.
Lastly, given a nested loop you can determine the result.
 LO24: You can describe the difference between a 1D and 2D
array. You can also declare an array with the correct number of
elements, in the correct location within your code and with the
correct data type. In addition, you understand when to declare
an array empty and how to use the ReDim statement.
 LO25: You can assign values to a 1D array as well as assign the
values of a 1D array to cells, a range or userform controls.
THE END

More Related Content

What's hot (19)

C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Arrays
ArraysArrays
Arrays
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
 
Arrays
ArraysArrays
Arrays
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
07slide
07slide07slide
07slide
 
Arrays
ArraysArrays
Arrays
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Unit 4 tree
Unit 4   treeUnit 4   tree
Unit 4 tree
 

Similar to Loops Arrays Excel VBA Lecture

Vb6 ch.8-3 cci
Vb6 ch.8-3 cciVb6 ch.8-3 cci
Vb6 ch.8-3 cciFahim Khan
 
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxAbhimanyuChaure
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Ggplot2 work
Ggplot2 workGgplot2 work
Ggplot2 workARUN DN
 
Algebra 2 unit 12
Algebra 2 unit 12Algebra 2 unit 12
Algebra 2 unit 12Mark Ryder
 
Advanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptAdvanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptMuhammad Sikandar Mustafa
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
 

Similar to Loops Arrays Excel VBA Lecture (20)

MA3696 Lecture 6
MA3696 Lecture 6MA3696 Lecture 6
MA3696 Lecture 6
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
Vb6 ch.8-3 cci
Vb6 ch.8-3 cciVb6 ch.8-3 cci
Vb6 ch.8-3 cci
 
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
 
Ma3696 lecture 4
Ma3696 lecture 4Ma3696 lecture 4
Ma3696 lecture 4
 
Array and functions
Array and functionsArray and functions
Array and functions
 
INTRODUCTION TO STATA.pptx
INTRODUCTION TO STATA.pptxINTRODUCTION TO STATA.pptx
INTRODUCTION TO STATA.pptx
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Ch08
Ch08Ch08
Ch08
 
Arrays
ArraysArrays
Arrays
 
Deep Factor Model
Deep Factor ModelDeep Factor Model
Deep Factor Model
 
Ggplot2 work
Ggplot2 workGgplot2 work
Ggplot2 work
 
Algebra 2 unit 12
Algebra 2 unit 12Algebra 2 unit 12
Algebra 2 unit 12
 
Advanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptAdvanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter ppt
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
 
Pemrograman Terstruktur 4
Pemrograman Terstruktur 4Pemrograman Terstruktur 4
Pemrograman Terstruktur 4
 
‏‏Lecture 2.pdf
‏‏Lecture 2.pdf‏‏Lecture 2.pdf
‏‏Lecture 2.pdf
 

More from Brunel University (7)

MA3696 Lecture 9
MA3696 Lecture 9MA3696 Lecture 9
MA3696 Lecture 9
 
MA3696 Lecture 8
MA3696 Lecture 8MA3696 Lecture 8
MA3696 Lecture 8
 
MA3696 Lecture 7
MA3696 Lecture 7MA3696 Lecture 7
MA3696 Lecture 7
 
Ma3696 Lecture 3
Ma3696 Lecture 3Ma3696 Lecture 3
Ma3696 Lecture 3
 
Ma3696 Lecture 2
Ma3696 Lecture 2Ma3696 Lecture 2
Ma3696 Lecture 2
 
Ma3696 Lecture 0
Ma3696 Lecture 0Ma3696 Lecture 0
Ma3696 Lecture 0
 
Ma3696 Lecture 1
Ma3696 Lecture 1Ma3696 Lecture 1
Ma3696 Lecture 1
 

Recently uploaded

M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis UsageNeil Kimberley
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdfOrient Homes
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...anilsa9823
 
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsCash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsApsara Of India
 
Non Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxNon Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxAbhayThakur200703
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
GD Birla and his contribution in management
GD Birla and his contribution in managementGD Birla and his contribution in management
GD Birla and his contribution in managementchhavia330
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechNewman George Leech
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Serviceankitnayak356677
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service JamshedpurVIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service JamshedpurSuhani Kapoor
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessAggregage
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 

Recently uploaded (20)

M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdf
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsCash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
 
Non Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxNon Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptx
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
GD Birla and his contribution in management
GD Birla and his contribution in managementGD Birla and his contribution in management
GD Birla and his contribution in management
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman Leech
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
 
KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service JamshedpurVIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for Success
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 

Loops Arrays Excel VBA Lecture

  • 2. SUMMARY Looping userform controls Generalising loops Nested For-Next loops 1D Arrays
  • 4. LOOPING USERFORM CONTROLS Labels 1, 2 and 3 Public Sub Command_LoopControls_Click() Label1.Caption = Cells(2, 2).Value Label2.Caption = Cells(2, 3).Value Label3.Caption = Cells(2, 4).Value End Sub These values are changing
  • 5. LOOPING USERFORM CONTROLS Public Sub Command_LoopControls_Click() i=1 i=2 i=3 Label1.Caption = Cells(2, 2).Value Label2.Caption = Cells(2, 3).Value Label3.Caption = Cells(2, 4).Value End Sub The label is i The column is i + 1
  • 6. LOOPING USERFORM CONTROLS The (Name) of the userform control
  • 10. EXERCISE 1. WRITE A FOR LOOP Download Lecture 5 Student Example.xlsm Write a For-Loop for this code in UserForm1.  Remember to declare your counter! Public Sub LoopExercise1_Click() Range(“Investment”).Columns(1).Value = TextBox1.Value Range(“Investment”).Columns(2).Value = TextBox2.Value Range(“Investment”).Columns(3).Value = TextBox3.Value End Sub Questions:  Are the cells being assigned the value of the textboxes?  Or are the textboxes being assigned the values of the cells?
  • 12. NESTED FOR-NEXT LOOP Repeat this twice For i = 1 to 3 Cells(i, 1).Value = i Next i ?
  • 13. NESTED FOR-NEXT LOOP Repeat this twice For k = 1 to 2 For i = 1 to 3 Cells(i, 1).Value = i Next i Next k
  • 14. NESTED FOR-NEXT LOOP Repeat this twice For i = 1 to 3 Cells(i, 1).Value = i Next i For k = 1 to 2 For i = 1 to 3 Cells(i, 1).Value = i Next i Next k
  • 15. NESTED FOR-NEXT LOOP Repeat this twice For i = 1 to 3 Cells(i, 1).Value = i Next i For k = 1 to 2 For i = 1 to 3 Cells(i, k).Value = i Next i Next k
  • 16. EXERCISE 2. NESTED FOR-NEXT LOOP Use Lecture 5 Student Example.xlsm  LoopExercise2 in Module1 Write a nested For-Loop for this output.  Remember to declare your counter. Repeat this twice
  • 17. EXERCISE 2. SOLUTIONS Cells(1, 1).Value = 1 Cells(1, 2).Value = 2 Cells(1, 3).Value = 3 Cells(2, 1).Value = 1 Cells(2, 2).Value = 2 Cells(2, 3).Value = 3 For i = 1 to 3 Cells(1, i).Value = i Next i Repeat this twice
  • 18. EXERCISE 2. SOLUTIONS Cells(1, 1).Value = 1 Cells(1, 2).Value = 2 Cells(1, 3).Value = 3 Cells(2, 1).Value = 1 Cells(2, 2).Value = 2 Cells(2, 3).Value = 3 For k = 1 to 2 For i = 1 to 3 Cells(1, i).Value = i Next i Next k
  • 19. EXERCISE 2. SOLUTIONS Cells(1, 1).Value = 1 Cells(1, 2).Value = 2 Cells(1, 3).Value = 3 Cells(2, 1).Value = 1 Cells(2, 2).Value = 2 Cells(2, 3).Value = 3 For k = 1 to 2 For i = 1 to 3 Cells(k, i).Value = i Next i Next k
  • 20. EXERCISE 3. NESTED FOR-NEXT LOOPS Use Lecture 5 Student Example.xlsm  LoopExercise3 in Module1 Write a nested For-Loop for this output.  Remember to declare your counter. Repeat this three times
  • 22. WHAT DOES IT MEAN TO GENERALISE? Dim i As Integer For i = 1 to 10 Cells(i +1, 1).Value = i Next i I know the number Dim i As Integer of TIMEPERIODS in advance Const TIMEPERIODS = 10 For i = 1 to TIMEPERIODS Cells(i +1, 1).Value = i Next i
  • 23. WHAT DOES IT MEAN TO GENERALISE? Unknown until the user runs the program Dim i As Integer Dim nStocksSelected As Integer For i = 1 to nStocksSelected […..] Next i I only want this code to run for the number of stocks selected by the user
  • 24. WHAT DOES IT MEAN TO GENERALISE? Replace specific numbers with variables  And assign those variables a value Enables code to be changed/updated quickly  Only have to change one value instead of every value Enables you to use user inputs in your loops  You don’t know these in advance
  • 26. ARRAYS Hold a range (or set) of values Basically a set of variables Your arrays will mainly be 1 or 2 dimensions arrayName(5) arrayName(5) arrayName(5, 4) arrayName is the name of your array
  • 27. ARRAYS Hold a range (or is onlyvalues 1D Arrays set) of about Today Basically a set of variables Your arrays will mainly be 1 or 2 dimensions arrayName(5) arrayName(5) arrayName(5, 4) arrayName is the name of your array
  • 28. DECLARING ARRAYS The same rules apply to arrays as to variables  Disposable, local or global? – Declare in the right place  Must specify a data type Also, need to specify the size of the array  The “size” is the number of elements in the array Public Sub DescriptiveStats() 5 stock prices Dim stockPrices(5) As Double Dim stockRet(4) As Double End Sub 4 stock returns
  • 29. DECLARING ARRAYS 5 stock prices 4 stock returns The same rules apply to arrays as to variables  Disposable, local or global? – Declare in the right place  Must specify a data type Also, need to specify the size of the array  The “size” is the number of elements in the array Public Sub DescriptiveStats() 5 stock prices Dim stockPrices(5) As Double Dim stockRet(4) As Double End Sub 4 stock returns
  • 30. DECLARING ARRAYS Many times we don’t know the number of elements that will be in the array. So, first declare them empty (disposable, local or global): Dim stockPrices() As Double For example, Dim stockRet() As Double these are local Public Sub DescriptiveStats() End Sub General format for declaration arrayName() As DataType arrayName:= the name of the array DataType:= Integer, Double, String…
  • 31. DECLARING ARRAYS After the size of the array is know, re-declare it inside a procedure Dim stockPrices() As Double Dim stockRet() As Double Dim nDays As Integer Public Sub DescriptiveStats() nDays = Combobox1.value ReDim stockPrices(nDays) As Double ReDim stockRet(nDays-1) As Double End Sub Arrays will most likely need to be local or global User selects number of days from a ComboBox on the userform Redim both arrays using the variable
  • 32. DECLARING ARRAYS After the size of the array is know, re-declare it inside a procedure General format for re-declaration ReDim arrayName(n) As DataType n:= the number of elements in the array
  • 33. ARRAYS VBA counts elements of arrays starting with 0 For example,  This array is named StockPrices  It has 5 elements (i.e., 5 stock prices) Count 0 1 StockPrices(1) 2 3 StockPrices(2) StockPrices(3) 4 StockPrices(4) StockPrices(0)
  • 34. ARRAYS To force VBA to count from 1  Use Option Base 1 at the top of each module Count 1 2 StockPrices(2) 3 4 StockPrices(3) StockPrices(4) 5 StockPrices(5) StockPrices(1)
  • 35. BEFORE ARRAYS… We had to declare multiple variables like this: And assign values like this:
  • 36. WITH ARRAYS… We can declare an array like this: And assign values like this:
  • 37. FILLING ARRAYS FROM CELLS OR RANGES A 1D array and a single For-Next loop so this is only for Stock 1 i=1 i=2 i=3 i=4 i=5 . . . i=9
  • 38. FILLING ARRAYS FROM CELLS OR RANGES Cells(1,1) i=1 i=2 i=3 i=4 i=5 . . . i=9 A 1D array and a single For-Next loop so this is only for Stock 1 Range Named “Prices”
  • 39. FILLING ARRAYS IN GENERAL You can ‘fill’ arrays with values from…  Cells  Ranges  Userform controls  Other variables or arrays  Using equations (e.g., calculate returns)
  • 40. OUTPUTTING ARRAYS TO CELLS OR RANGES i=1 i=2 i=3 i=4 i=5 **This is assuming we have assigned each element of the array weights() a value**
  • 41. OUTPUTTING ARRAYS TO CELLS OR RANGES Range Named “StockWeights” Cells(1,1) i=1 i=2 i=3 i=4 i=5 **This is assuming we have assigned each element of the array weights() a value**
  • 42. OUTPUTTING ARRAYS IN GENERAL You can ‘output’ the value of arrays to…  Cells  Ranges  Userform controls  Other variables or arrays
  • 43. EXERCISE 4A. WRITE A FOR LOOP Use Lecture 5 Student Example.xlsm  LoopExercise4A in Module1 Declare an array for stock returns Use that array in a For-Loop to rewrite this code.  Remember to declare your counter! Public Sub LoopExercise4A() stockRet1 = Cells(4, 6).Value stockRet2 = Cells(5, 6).Value stockRet3 = Cells(6, 6).Value End Sub
  • 44. EXERCISE 4B. WRITE A FOR LOOP Now, instead of using cell references use range references to assign the array values: Public Sub LoopExercise4A() stockRet1 = Cells(4, 6).Value stockRet2 = Cells(5, 6).Value stockRet3 = Cells(6, 6).Value End Sub Public Sub LoopExercise4B() stockRet1 = Range(“Returns”).Cells(1, 1) stockRet2 = Range(“Returns”).Cells(2, 1) stockRet3 = Range(“Returns”).Cells(3, 1) End Sub Exercise 4A Exercise 4B Check your array has correct values by either:  Outputting the array values to different cells (any cells)  Or by using a message box  Or by stepping through your code and checking the value of each array element.
  • 45. WRITE SUMS USING LOOPS & ARRAYS sum = stockPrice(1) + stockPrice(2) + stockPrice(3)
  • 46. WRITE SUMS USING LOOPS & ARRAYS sum = stockPrice(1) + stockPrice(2) + stockPrice(3) i=1 i = 1 sum = stockPrice(1)
  • 47. WRITE SUMS USING LOOPS & ARRAYS sum = stockPrice(1) + stockPrice(2) + stockPrice(3) i=1 i=2 i = 1 sum = stockPrice(1) i = 2 sum = sum + stockPrice(2)
  • 48. WRITE SUMS USING LOOPS & ARRAYS sum = stockPrice(1) + stockPrice(2) + stockPrice(3) i=1 i=2 i=3 i = 1 sum = stockPrice(1) i = 2 sum = sum + stockPrice(2) i = 3 sum = sum + stockPrice(3)
  • 49. WRITE SUMS USING LOOPS & ARRAYS sum = stockPrice(1) + stockPrice(2) + stockPrice(3) i=1 i=2 i=3 sum = 0 i = 1 sum = sum + stockPrice(1) i = 2 sum = sum + stockPrice(2) i = 3 sum = sum + stockPrice(3)
  • 50. WRITE SUMS USING LOOPS & ARRAYS sum = stockPrice(1) + stockPrice(2) + stockPrice(3) Make sure the sum starts at 0
  • 51. EXERCISE 5. WRITE A FOR LOOP Use Lecture 5 Student Example.xlsm  LoopExercise4B in Module1 Find the sum of the 3 stock returns you assigned to an array in Exercise 4B using a For-Next loop. Check your sum with a message box. If you get the following result, you are correct:
  • 52. LEARNING OUTCOMES  You are ready to move on when:  LO21: You can use loops and concatenation to assign values to controls on a userform or assign cells, ranges or 1D arrays values from userform controls.  LO22: You can describe what it means to generalise code. You can also determine when loops should be generalised and how to do so within your code.  LO23: You can define what a nested loop is. You can also construct basic nested loops to output values to cells or ranges. Lastly, given a nested loop you can determine the result.  LO24: You can describe the difference between a 1D and 2D array. You can also declare an array with the correct number of elements, in the correct location within your code and with the correct data type. In addition, you understand when to declare an array empty and how to use the ReDim statement.  LO25: You can assign values to a 1D array as well as assign the values of a 1D array to cells, a range or userform controls.