2D Arrays Algorithms LECTURE 6
2D Arrays
Algorithms LECTURE 6
Quick recap of 1D arrays
2D Arrays
Declaring and re-declaring
Assigning values
Outputting values
Algorithms
Mapping out the tasks needed for a program
SUMMARY
Const TIMEPERIODS as Integer = 4 Dim stockReturns(TIMEPERIODS) as Double
Const NSTOCKS as Integer = 2 ReDim meanRet(NSTOCKS) as Double
REVIEW OF 1D ARRAYS
**Assume we’re using Option Base 1**
REVIEW OF 1D ARRAYS
stockReturns(2) = ? _
**Assume we’re using Option Base 1**
REVIEW OF 1D ARRAYS
stockReturns(2) = 0.0024
**Assume we’re using Option Base 1**
REVIEW OF 1D ARRAYS
stockReturns(4) = ? _
**Assume we’re using Option Base 1**
REVIEW OF 1D ARRAYS
stockReturns(4) = 0.0052
**Assume we’re using Option Base 1**
REVIEW OF 1D ARRAYS
meanRet (1) = ? _
**Assume we’re using Option Base 1**
REVIEW OF 1D ARRAYS
meanRet (1) = 0.00371
**Assume we’re using Option Base 1**
2D ARRAYS
Hold a range (or set) of values
Basically a set of variables
Your arrays will mainly be 1 or 2 dimensions
arrayName is the name of your array
ARRAYS
arrayName(5) arrayName(5) arrayName(5, 4)
arrayName(5) arrayName(5)
Hold a range (or set) of values
Basically a set of variables
Your arrays will mainly be 1 or 2 dimensions
arrayName is the name of your array
ARRAYS
Today is about 2D Arrays
arrayName(5, 4)
The same rules apply to 2D arrays as to 1D arrays
Disposable, local or global? – Declare in the right place
Must specify a data type
DECLARING ARRAYS
Public Sub DescriptiveStats()
Dim stockPrices(5, 2) As Double
Dim stockRet(4, 2) As Double
End Sub
These are disposable
The same rules apply to 2D arrays as to 1D arrays
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
DECLARING ARRAYS
Public Sub DescriptiveStats()
Dim stockPrices(5, 2) As Double
Dim stockRet(4, 2) As Double
End Sub
5 rows 2 columns
4 rows 2 columns
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
DECLARING ARRAYS 5 stock prices 2 stocks
4 stock returns 2 stocks
Public Sub DescriptiveStats()
Dim stockPrices(5, 2) As Double
Dim stockRet(4, 2) As Double
End Sub
5 prices 2 stocks
4 returns 2 stocks
Many times we don’t know the number of elements that will be in the array.
So, first declare them empty, like this:
DECLARING ARRAYS (1D AND 2D)
Dim stockPrices() As Double Dim stockRet() As Double
Public Sub DescriptiveStats()
End Sub
arrayName() As DataType
arrayName:= the name of the array DataType:= Integer, Double, String…
General format for declaration
For example, these are local
After the size of the array is know, re-declare it inside a procedure
Dim stockPrices() As Double, stockRet() As Double Dim nDays As Integer, nStocks As Integer
DECLARING ARRAYS
Arrays will most likely need to be local or global
These are local
After the size of the array is know, re-declare it inside a procedure
Dim stockPrices() As Double, stockRet() As Double Dim nDays As Integer, nStocks As Integer
Public Sub DescriptiveStats()
nDays = ComboBox1.Value nStocks = ComboBox2.Value
End Sub
DECLARING ARRAYS
User selects number of days from a
ComboBox on the userform
After the size of the array is know, re-declare it inside a procedure
Dim stockPrices() As Double, stockRet() As Double Dim nDays As Integer, nStocks As Integer
Public Sub DescriptiveStats()
nDays = ComboBox1.Value nStocks = ComboBox2.Value
End Sub
DECLARING ARRAYS
User selects number of stocks from a
ComboBox on the userform
After the size of the array is know, re-declare it inside a procedure
Dim stockPrices() As Double, stockRet() As Double Dim nDays As Integer, nStocks As Integer
Public Sub DescriptiveStats()
nDays = ComboBox1.Value nStocks = ComboBox2.Value
Redim stockPrices(nDays, nStocks) As Double Redim stockRet(nDays-1, nStocks) As Double
End Sub
DECLARING ARRAYS
Redim both arrays using the variables
After the size of the array is know, re-declare it inside a procedure
Dim stockPrices() As Double, stockRet() As Double Dim nDays As Integer, nStocks As Integer
Public Sub DescriptiveStats()
nDays = ComboBox1.Value nStocks = ComboBox2.Value
Redim stockPrices(nDays, nStocks) As Double Redim stockRet(nDays-1, nStocks) As Double
End Sub
DECLARING ARRAYS
Num Rows Num Cols
After the size of the array is know, re-declare it inside a procedure
DECLARING ARRAYS
ReDim arrayName(nRows, nCols) As DataType
nRows:= the number of rows in the array nCols:= the number of columns in the array
General format for re-declaration
If the size of the array is known and constant
Declare the constants for nRows and nCols as global
Declare the arrays (disposable, local or global) using the constants as the nRows and nCols
SUMMARY OF DECLARING 2D ARRAYS
Public Const TIMEPERIODS As Integer = 5Public Const NSTOCKS As Integer = 2
Dim stockPrices(TIMEPERIODS, NSTOCKS) As DoubleDim stockRet(TIMEPERIODS-1, NSTOCKS) As Double
Remember to use Public instead of Dim if they are global.
If the size of the array is unknown or variable
Declare the arrays empty (disposable, local or global)
SUMMARY OF DECLARING 2D ARRAYS
If the size of the array is unknown or variable
Declare the arrays empty (disposable, local or global)
Declare variables for nRows and nCols (disposable, local or global) and assign them values
SUMMARY OF DECLARING 2D ARRAYS
If the size of the array is unknown or variable
Declare the arrays empty (disposable, local or global)
Declare variables for nRows and nCols (disposable, local or global) and assign them values
Redim the arrays using the variables
SUMMARY OF DECLARING 2D ARRAYS
VBA counts elements of 1D and 2D arrays from 0
For example,
This array is named stockPrices
It has 5 rows and 2 columns: stockPrices(5, 2)
2D ARRAYS
stockPrices(0, 0)
Count
0 1 2 3 4
0 1
VBA counts elements of 1D and 2D arrays from 0
For example,
This array is named stockPrices
It has 5 rows and 2 columns: stockPrices(5, 2)
2D ARRAYS
stockPrices(4, 1)
Count
0 1 2 3 4
0 1
To force VBA to count from 1
Use Option Base 1 at the top of each module
2D ARRAYS
stockPrices(1, 1)
Count
1 2 3 4 5
1 2
To force VBA to count from 1
Use Option Base 1 at the top of each module
2D ARRAYS
stockPrices(5, 2)
Count
1 2 3 4 5
1 2
Use Lecture 6 Student Example.xlsm , Module1
Declare an array to store the stock returns shown:
The array can be declared as disposable, local or global.
Assume you know in advance that: nRows is the constant TIMEPERIODS
nCols is the constant NSTOCKS
EXERCISE 1. DECLARING 2D ARRAYS
Use Lecture 6 Student Example.xlsm , Module1
Declare an array to store the stock returns shown:
The array can be declared as disposable, local or global.
Assume that nRows and nCols are NOT known in advance: nRows is the variable nTimePeriods. Assign a value in the procedure
nCols is the variable nStocks. Assign a value in the procedure
EXERCISE 2. DECLARING 2D ARRAYS
‘FILLING’ ARRAYS USING NAMED RANGES
FILLING 1D ARRAYS FROM A NAMED RANGE
Range(“StockPrices”).Cells(1, 1)
Range(“StockPrices”).Cells(2, 1)
Range(“StockPrices”).Cells(3, 1)
Range(“StockPrices”).Cells(10,1)
FILLING 1D ARRAYS FROM A NAMED RANGE
For i = 1 to TIMPERIODSstockPrices(i) = Range(“StockPrices”).Cells(i,1)
Next i
FILLING 2D ARRAYS FROM A NAMED RANGE
Range(“StockPrices”).Cells(1, 1)
Range(“StockPrices”).Cells(2, 1)
Range(“StockPrices”).Cells(3, 1)
Range(“StockPrices”).Cells(10,1)
FILLING 2D ARRAYS FROM A NAMED RANGE
Range(“StockPrices”).Cells(1, 2)
Range(“StockPrices”).Cells(2, 2)
Range(“StockPrices”).Cells(3, 2)
Range(“StockPrices”).Cells(10,2)
FILLING 2D ARRAYS FROM A NAMED RANGE
For k = 1 to NSTOCKSFor i = 1 to TIMPERIODS
stockPrices(i,k) = Range(“StockPrices”).Cells(i,k)Next i
Next k
OUTPUTTING ARRAYS USING NAMED RANGES
OUTPUTTING 1D ARRAY TO A NAMED RANGE
Range(“StockReturns”).Cells(1, 1)
Range(“StockReturns”).Cells(2, 1)
Range(“StockReturns”).Cells(3, 1)
Range(“StockReturns”).Cells(9,1)
OUTPUTTING 1D ARRAY TO A NAMED RANGE
For i = 1 to TIMPERIODS - 1Range(“StockReturns”).Cells(i,1) = stockReturns(i)
Next i
OUTPUTTING 1D ARRAY TO A NAMED RANGE
Range(“StockReturns”).Cells(1, 1)
Range(“StockReturns”).Cells(2, 1)
Range(“StockReturns”).Cells(3, 1)
Range(“StockReturns”).Cells(9,1)
OUTPUTTING 1D ARRAY TO A NAMED RANGE
Range(“StockReturns”).Cells(1, 2)
Range(“StockReturns”).Cells(2, 2)
Range(“StockReturns”).Cells(3, 2)
Range(“StockReturns”).Cells(9,2)
OUTPUTTING 1D ARRAY TO A NAMED RANGE
Use Lecture 6 Student Example.xlsm , Module1
Read in the prices from the range “PricesPence” to an array with the same name
Convert the pence to pounds and assign the values to an array called PricesPounds()
Output the values of PricesPounds() to the named range “PricesPounds”
REMEMBER: Generalise your code!
Ranges have been named.
EXERCISE 3. FILL AND OUTPUT
ALGORITHMS
Taking a road trip
Just get in the car and drive, OR
Make a plan and print directions (or set the sat nav)?
When you write a program
Go straight to VBA and try typing some code? NO!
Make a plan first!
Why is this so difficult?
The plan is usually written for you (assignments, labs, etc…). You just have to follow the steps already given.
When you write a program/software, there are no steps given – you have to write them.
THINK ABOUT THE PROCESS
(A few) questions you should answer first:
What will the user want to achieve with this software? Portfolio optimisation, simulation, risk analysis, etc…?
What tasks are needed in order to get the end result? Select stocks, assign weights, choose capital to invest, etc…?
What are the steps for each task? Will they select stocks from a list, will they enter weights or
investments, navigate with command buttons, etc…?
What tools are used to complete the steps for each task? Includes userform controls as well as programing tools?
Where does the information for each task come from? Are stock prices already in the spread sheet or downloaded from
the internet, what information is entered by the user, etc…?
TASK ANALYSIS ( J O H N S O N , 2 0 1 0 )
What is the result/output of each task?
How will the result of each task be used? Count how many stocks are chosen, output chosen stocks on a
separate sheet, etc…?
What problems may users have in doing these tasks? Will they know what order to do things & understand instructions?
What are common user mistakes? Entering decimal numbers instead of integers, trying to move
forward without completing all steps, etc…?
How will you deal with these errors when they occur?
What terminology will the user be familiar with? Can they understand your lingo?
TASK ANALYSIS (CONT’D) ( J O H N S O N , 2 0 1 0 )
You cannot write a complicated program without planning.
Break everything down into simple steps
You will never write a ‘perfect’ program without first making mistakes
Trial and error – that’s part of programming
Just because it doesn’t work the first time, don’t give up
If something isn’t ‘working’ it’s probably an error on your part, not VBA.
The hardest part of creating a program is writing out the process. Usually, the actual code is fairly straight forward.
BREAKING DOWN A COMPLICATED TASK
EXAMPLE ALGORITHM
Task 1: Select a time period
Task 2: Enter investments
Task 3: Click ‘Estimate return’ button
Task 4: Review investment on next userform.
Task 5: Click ‘Change investment’ button
Task 6: Click ‘Quit’ button
EXAMPLE. BREAKING DOWN TASKS
User selects time from combobox
Fill combobox BEFORE user sees Userform initialise: add items
When the user selects a time: Name the range of prices
corresponding to that time
Use that range to calculate stats
I’ll need the means later, so assign those to an array first
Then use the array of means to assign values to the labels.
Display those stats on the userform
Format the display to be %
Enable the textboxes
EXAMPLE. TASK 1 – SELECT TIME
The user enters investments in the textboxes.
EXAMPLE. TASK 2 - INVESTMENTS
Check user entries: Check for letters, blanks & negative
numbers
I’ll need to use investments in a calculation so assign them to an array.
Calculate total investment Add together all investments
Calculate the final value Need means and investments
Calculate the return (final value/total investment)–1
Show the next userform
EXAMPLE. TASK 3 – CLICK BUTTON
Output should display BEFORE the user sees the form (initialise sub)
Display total investment (£)
Assign the label the value of the total investment variable
Format label as £0.00
Display portfolio return
Assign the label the value of the portfolio return variable
Format label as 0.000%
Display final investment value (£)
Assign the label the value of the final investment variable
Format label as £0.00
EXAMPLE. TASK 4 – REVIEW RESULTS
User wants to change their investments: Unload the investment summary
userform
EXAMPLE. TASK 5 – CHANGE INVESTMENT
User wants to quit the program: Ask user if they are sure they want to
quit as this will close the program
If yes, then unload both userforms
If no, then do nothing
EXAMPLE. TASK 6 – QUIT
You are ready to move on when…
LO26: You can declare a 2D 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.
LO27: You can assign values to a 2D array as well as assign the values of a 2D array to cells, a range or userform controls.
LO28: You can list the questions we should ask when developing a program. You can describe what is meant by a ‘task’ as part of a program. Lastly, you can identify the tasks of a program in order to construct an algorithm.
LEARNING OUTCOMES
THE END