SlideShare a Scribd company logo
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

PPT
Arrays
PPT
Array
PDF
Java chapter 6 - Arrays -syntax and use
PDF
Array and Collections in c#
PPT
Data Structure and Algorithms Arrays
PDF
LectureNotes-05-DSA
PPTX
Chapter 15 Lists
PPTX
6 arrays injava
Arrays
Array
Java chapter 6 - Arrays -syntax and use
Array and Collections in c#
Data Structure and Algorithms Arrays
LectureNotes-05-DSA
Chapter 15 Lists
6 arrays injava

What's hot (19)

PPT
C++ Arrays
PPTX
C# Arrays
PDF
Python Workshop Part 2. LUG Maniapl
PDF
LectureNotes-02-DSA
PPTX
Chap1 array
PPT
PPTX
Arrays in programming
PPT
Arrays in C++
PDF
Arrays In Python | Python Array Operations | Edureka
PPTX
Datastructures in python
PDF
Arrays in python
PPT
9781439035665 ppt ch09
PPT
Arrays and structures
PPT
PDF
Python data handling notes
PDF
LectureNotes-03-DSA
PPT
Unit 4 tree
C++ Arrays
C# Arrays
Python Workshop Part 2. LUG Maniapl
LectureNotes-02-DSA
Chap1 array
Arrays in programming
Arrays in C++
Arrays In Python | Python Array Operations | Edureka
Datastructures in python
Arrays in python
9781439035665 ppt ch09
Arrays and structures
Python data handling notes
LectureNotes-03-DSA
Unit 4 tree
Ad

Similar to MA3696 Lecture 5 (20)

PDF
MA3696 Lecture 6
PDF
MA3696 Lecture 9
PDF
Ma3696 lecture 4
PDF
Ma3696 Lecture 3
PPT
Programming Logic and Design: Arrays
PDF
Advanced MATLAB Tutorial for Engineers & Scientists
PPTX
Array and functions
PDF
The Basics of MATLAB
PDF
Excel-Quick-Reference-Guide.pdf
DOC
Excel Vba Basic Tutorial 1
PPTX
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
DOCX
VBScript Functions procedures and arrays.docx
PPTX
Vba Class Level 1
PDF
Introduction to Programming Using Visual Basic 10th Edition Schneider Test Bank
PDF
Online Advance Excel & VBA Training in India
PDF
Ecdl v5 module 4 print
PPTX
Ma3696 Lecture 1
PDF
procedures and arrays
PDF
Excel vba notesforprofessionals
PDF
Getting started with Microsoft Excel Macros
MA3696 Lecture 6
MA3696 Lecture 9
Ma3696 lecture 4
Ma3696 Lecture 3
Programming Logic and Design: Arrays
Advanced MATLAB Tutorial for Engineers & Scientists
Array and functions
The Basics of MATLAB
Excel-Quick-Reference-Guide.pdf
Excel Vba Basic Tutorial 1
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
VBScript Functions procedures and arrays.docx
Vba Class Level 1
Introduction to Programming Using Visual Basic 10th Edition Schneider Test Bank
Online Advance Excel & VBA Training in India
Ecdl v5 module 4 print
Ma3696 Lecture 1
procedures and arrays
Excel vba notesforprofessionals
Getting started with Microsoft Excel Macros
Ad

Recently uploaded (20)

PPTX
operations management : demand supply ch
PPTX
Sales & Distribution Management , LOGISTICS, Distribution, Sales Managers
PPT
Lecture 3344;;,,(,(((((((((((((((((((((((
PPTX
2025 Product Deck V1.0.pptxCATALOGTCLCIA
PDF
Tata consultancy services case study shri Sharda college, basrur
PDF
Keppel_Proposed Divestment of M1 Limited
PPTX
sales presentation، Training Overview.pptx
PPTX
TRAINNING, DEVELOPMENT AND APPRAISAL.pptx
PDF
Blood Collected straight from the donor into a blood bag and mixed with an an...
PDF
Deliverable file - Regulatory guideline analysis.pdf
PDF
Cours de Système d'information about ERP.pdf
PPTX
Board-Reporting-Package-by-Umbrex-5-23-23.pptx
PDF
Introduction to Generative Engine Optimization (GEO)
PDF
NISM Series V-A MFD Workbook v December 2024.khhhjtgvwevoypdnew one must use ...
PDF
1911 Gold Corporate Presentation Aug 2025.pdf
PPTX
Slide gioi thieu VietinBank Quy 2 - 2025
PDF
Digital Marketing & E-commerce Certificate Glossary.pdf.................
PDF
NewBase 12 August 2025 Energy News issue - 1812 by Khaled Al Awadi_compresse...
PPTX
Principles of Marketing, Industrial, Consumers,
PDF
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions
operations management : demand supply ch
Sales & Distribution Management , LOGISTICS, Distribution, Sales Managers
Lecture 3344;;,,(,(((((((((((((((((((((((
2025 Product Deck V1.0.pptxCATALOGTCLCIA
Tata consultancy services case study shri Sharda college, basrur
Keppel_Proposed Divestment of M1 Limited
sales presentation، Training Overview.pptx
TRAINNING, DEVELOPMENT AND APPRAISAL.pptx
Blood Collected straight from the donor into a blood bag and mixed with an an...
Deliverable file - Regulatory guideline analysis.pdf
Cours de Système d'information about ERP.pdf
Board-Reporting-Package-by-Umbrex-5-23-23.pptx
Introduction to Generative Engine Optimization (GEO)
NISM Series V-A MFD Workbook v December 2024.khhhjtgvwevoypdnew one must use ...
1911 Gold Corporate Presentation Aug 2025.pdf
Slide gioi thieu VietinBank Quy 2 - 2025
Digital Marketing & E-commerce Certificate Glossary.pdf.................
NewBase 12 August 2025 Energy News issue - 1812 by Khaled Al Awadi_compresse...
Principles of Marketing, Industrial, Consumers,
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions

MA3696 Lecture 5

  • 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.