Transcript

Intro to Variables and Constants

LECTURE 3

Using variables & constants in VBA

Declarations and data types

Naming

Assigning values

‘Option Explicit’ – use this to catch errors

Structuring code

Commenting code

Making comments about your code

Commenting out parts of code so they don’t run

A few extra bits at the end

Show/hide a userform during a program

Formatting numbers

SUMMARY

Declare,

Data type,

& Name VARIABLES & CONSTANTS

The number of time periods

TIMEPERIODS = 15

The total number of stocks

NUMSTOCKS = 50

KNOWING THE DIFFERENCE…

Constants Their value stays constant and does not change.

KNOWING THE DIFFERENCE…

Variables Their value can be changed - it’s not fixed, but variable.

A stocks return

stockRet = 𝐹𝑖𝑛𝑎𝑙 𝑝𝑟𝑖𝑐𝑒

𝐼𝑛𝑖𝑡𝑖𝑎𝑙 𝑝𝑟𝑖𝑐𝑒− 1

The portfolio return (sum of: weights (w i) * stock returns (r i))

portfolioRet = w1*r1 + w2*r2 + w3*r3

In general, a variable is…

Any value requiring a calculation

Any value that is not known at the start of the program

Any value that may change during the program

Specify the data type of each constant & variable

Integer No decimal places; can be pos. or neg.

String Text (i.e., words)

Double A very large or very small number

(there are other types as well, they ’ll be introduced when needed).

KNOWING THE DIFFERENCE…

Constants Their value stays constant and does not change.

Variables Their value can be changed - it’s not fixed, but variable.

Constants…

Why not just use the number?

Variables…

Why not just use cells and userform controls in an equation?

WHY USE VARIABLES OR CONSTANTS?

If you need to change is value… You only have to change one value instead of every value!

• Prevents errors from using controls in equations

• Equations are easier to read

• Overall, you code is easier to read

Declare disposable variables and constants within the procedure you want to use them.

constantName = the name of your constant

variableName = the name of your variable

dataType = the data type (integer, string, double…)

value = the value of the constant

DIFFERENT USES – DIFFERENT LOCATIONS

Disposable (aka ‘Procedure only’)

• They keep their value ONLY in a specific procedure. • Their value cannot be accessed from a different procedure.

Const constantName As dataType = value

Dim variableName As dataType

Constant

Variable

Declare disposable variables and constants within the procedure you want to use them.

DIFFERENT USES – DIFFERENT LOCATIONS

Disposable (aka ‘Procedure only’)

• They keep their value ONLY in a specific procedure. • Their value cannot be accessed from a different procedure.

Public Sub DescriptiveStats()

Const TIMEPERIODS As Integer = 10

Dim portfolioRet As Double

End Sub

They will only exist and have a value inside this procedure

Declare local variables & constants at the top of the module (or userform module) you want to use them.

constantName = the name of your constant

variableName = the name of your variable

dataType = the data type (integer, string, double…)

value = the value of the constant

DIFFERENT USES – DIFFERENT LOCATIONS

Const constantName As dataType = value

Dim variableName As dataType

Constant

Variable

Local (aka ‘Module only’)

• They keep their value within a specific module. • Access their stored value within any procedure in that module

Declare local variables & constants at the top of the module (or userform module) you want to use them.

DIFFERENT USES – DIFFERENT LOCATIONS

Local (aka ‘Module only’)

• They keep their value within a specific module (or userform module). • Access their stored value within any procedure in that module

Const TIMEPERIODS As Integer = 10 Dim portfolioRet As Double

Public Sub DescriptiveStats() (code goes here) End Sub Public Sub OptimisePortfolio() (code goes here) End Sub

They can be used in ANY procedure

in THIS module and their value will be

remembered.

Declare global variables & constants at the top of a module (but not a userform module).

constantName = the name of your constant

variableName = the name of your variable

dataType = the data type (integer, string, double…)

value = the value of the constant

DIFFERENT USES – DIFFERENT LOCATIONS

Public Const constantName As dataType = value

Public variableName As dataType

Constant

Variable

Global • They keep their value as long as the program is running. • Access their stored value within any procedure in any module or userform

Declare global variables & constants at the top of a module (but not a userform module).

It’s best to have one module for ALL global variables

This way you can easily keep track of them

DIFFERENT USES – DIFFERENT LOCATIONS

Global • They keep their value as long as the program is running. • Access their stored value within any procedure in any module or userform

Public Const TIMEPERIODS As Integer = 10 Public portfolioRet As Double

They can be used in ANY procedure

in ANY module and their value will be

remembered.

DIFFERENT USES – DIFFERENT LOCATIONS

Disposable (Procedure-only)

• Declare these within the procedure you want to use them.

Local (Module-only)

• Declare these at the top of the specific module (or userform module) in which you want to use them.

Global (Used anywhere)

• Declare these at the top of any module (but not a userform module).

DIFFERENT USES – DIFFERENT LOCATIONS

Disposable (Procedure-only)

• Declare these within the procedure you want to use them.

Local (Module-only)

• Declare these at the top of the specific module (or userform module) in which you want to use them.

Global (Used anywhere)

• Declare these at the top of any module (but not a userform module).

DIFFERENT USES – DIFFERENT LOCATIONS

Disposable (Procedure-only)

• Declare these within the procedure you want to use them.

Local (Module-only)

• Declare these at the top of the specific module (or userform module) in which you want to use them.

Global (Used anywhere)

• Declare these at the top of any module (but not a userform module).

Constants…

Are assigned a value in the declaration statement

Const TIMEPERIODS As Integer = 10 Public Const TIMEPERIODS As Integer = 10

Variables…

Are NOT assigned values in the declaration statement

Dim portfolioRet As Double Public portfolioRet As Double

Assign each variable a value within a procedure

ASSIGNING VALUES

Public Sub DescriptiveStats()

portfolioRet = w1*r1 + w2*r2 + w3*r3

End Sub

Any value(s) from…

A single cell or named range in excel

A userform control (e.g., textbox, combobox, etc…)

…that will be used in a calculation, should be declared as a variable.

For example,

WHICH SHOULD BE DECLARED?

Shown on next slide

Estimate Portfolio Value

All 4 values (both means and investment values) are needed to calculate the portfolio’s return

All 4 values need to be assigned to variables

The variables should be used in calculations

VARIABLE – EXAMPLE PROGRAM

I’ve declared the variables first (these are local)

I’ve assigned each a value within the procedure

To calculate portfolioValue I’ll use these variables

VARIABLE – EXAMPLE PROGRAM

Just about any name except a keyword in VBA (which will be green or blue)

Short & concise, yet descriptive:

You need to remember it

Others reading your code need to understand it

No spaces or special characters, except “_”

USING PROPER NAMES

The number of time periods

TIMEPERIODS = 15

The total number of stocks

NUMSTOCKS = 50

USING PROPER NAMES

Constants Typically all capital letters (helps distinguish from Variables)

USING PROPER NAMES

Variables • Begin with a lower case letter • If joining 2 or more words, CAPITALISE the first letter of each

word

A stocks return

stockRet = 𝐹𝑖𝑛𝑎𝑙 𝑝𝑟𝑖𝑐𝑒

𝐼𝑛𝑖𝑡𝑖𝑎𝑙 𝑝𝑟𝑖𝑐𝑒− 1

The portfolio return (sum of weights (w) * stock returns (r))

portfolioRet = w1*r1 + w2*r2 + w3*r3

Final investment value (capital invested * (1+ portfolio return))

finalValue = capInvest * (1 + portfolioRet)

EXERCISE. DECLARING VARIABLES

Insert a new module and procedure.

Declare a disposable integer variable called x.

Assign x an initial value of 0.

Declare a global constant called TIMEPERIODS.

There are 250 time periods.

Declare a global variable called nStocks.

Assign nStocks a value of 30.

Declare a local variable called portfolioRet.

Assign portfolioRet the value of Cells(1,1).

Enter any value into Cells(1,1)

Use Msgboxes to check you have done each right

Write at the very TOP of EVERY module

Forces all variables and constants to be declared

Any undeclared variables or constants will cause an error.

‘OPTION EXPLICIT’

WHY USE ‘OPTION EXPLICIT’?

To ensure variables are given a correct data type (e.g. Integer, Double, string, etc...)

VBA assigns any undeclared variables as Variant

This takes more memory

It can make your code run slower.

To help catch misspelled variables.

Essentially, it ’s a good way to catch mistakes.

Most common mistakes

ASSIGNING VALUES

When x was assigned the value of y, y did not have a value

VBA will not ‘remember ’ that x = y and assign x the correct value of y later in the code

VBA runs code line by line

ASSIGNING VARIABLE VALUES

What will be the value of x after running this Sub?

This way is correct!

Assign x the value of y AFTER y has a value

ASSIGNING VARIABLE VALUES

What will be the value of x after running this Sub?

STRUCTURING CODE

STRUCTURING CODE

Declare all local variables and constants

Declare all disposable variables and constants

Sub procedure()

Assign initial values to variables

The rest of your code should follow In a logical order (code runs in the order you put it)

End Sub

STRUCTURING CODE

Declare all local variables and constants

Declare some disposable variables & constants

Sub procedure()

Assign some initial values to variables

Some code

End Sub

Declare more disposable variables & constants

Assign more initial values to variables

Some code

STRUCTURING CODE

Declare all local variables and constants

Declare all disposable variables and constants

Sub procedure()

Assign initial values to variables

The rest of your code should follow In a logical order (code runs in the order you put it)

End Sub

COMMENTING CODE

Comment out lines of code using ‘

Commented code…

Turns green

Is not executed when the procedure is run

COMMENTING ‘OUT’ CODE

Test part of the code, without running it all .

Good for debugging your code.

Code you don’t want to run, but don’t want to delete either.

Can’t figure out what’s wrong with some code, and want to save it until you can get help, but meanwhile want to run the remaining code.

WHY COMMENT OUT CODE?

Look for the ‘Edit toobar at the top

COMMENT OUT BLOCKS OF CODE

Comment out code Highlight the code Press this icon

Look for the ‘Edit toobar at the top

COMMENT OUT BLOCKS OF CODE

Uncomment out code Highlight the code Press this icon

Don’t see this toolbar?

Right click somewhere along the menu bar

Select ‘Edit’

The edit bar will appear

COMMENT OUT BLOCKS OF CODE

Use ‘ to make comments about your code

What it does and what it is for

MAKING COMMENTS IN YOUR CODE

You’ll need these for your lab

A FEW EXTRAS

If you want a userform to show (open)

NameOfUserform.Show

If you want a useform to unload (close)

Unload NameOfUserform

Unload Me

SHOW/UNLOAD USERFORMS

UserForm1.Show

Unload Userform1

Unload Me

OR

This code should be in a procedure

Format a number in a label caption

labelName.Caption = Format(value, “.000”)

labelName.Caption = Format(value, “£.00”)

labelName.Caption = Format(value, “.00%”)

FORMATTING NUMBERS

The value being formatted

Format a number in a label caption

labelName.Caption = Format(value, “.000”)

labelName.Caption = Format(value, “£.00”)

labelName.Caption = Format(value, “.00%”)

FORMATTING NUMBERS

The number of 0s is the number of decimal places you want the formatted number to have

Format a number in a label caption

labelName.Caption = Format(value, “.000”)

labelName.Caption = Format(value, “£.00”)

labelName.Caption = Format(value, “.00%”)

FORMATTING NUMBERS

A number with 3 decimal places (.000)

Label1.Caption = Format(0.0062159483, “.000”)

Format a number in a label caption

labelName.Caption = Format(value, “.000”)

labelName.Caption = Format(value, “£.00”)

labelName.Caption = Format(value, “.00%”)

FORMATTING NUMBERS

A number as currency (£) with 2 decimal places (.00)

Label1.Caption = Format(56.3, “£.00”)

Format a number in a label caption

labelName.Caption = Format(value, “.000”)

labelName.Caption = Format(value, “£.00”)

labelName.Caption = Format(value, “.00%”)

FORMATTING NUMBERS

A number as a percentage (%) with 2 decimal places (.00)

Label1.Caption = Format(0.003, “.00%”)

0.003 x 100% = .30%

Format(value, “.000”)

Value can be anything with a numerical value:

A userform control (as long as it’s value is a number). E.g.: Format(textbox1.value,…)

Format(combobox1.value,…)

Format(label1.value,…)

A variable (as long as it’s value is a number). E.g.: Format(xVar,…), where xVar is a variable

A cell or named range. E.g.: Format(Cells(1,1).value,…)

A result from a function Format(Application.WorksheetFunction.Sum(…),…)

Etc…

FORMATTING NUMBERS

Assign a formatted number to a label

labelName.Caption = Format(value, “.000”)

Assign a formatted number to a textbox

textboxName.value = Format(value, “.0000”)

You can assign a formatted number to

A userform control (e.g., label, textbox, etc…)

A cell or named range Cells(1,1) = Format(value, “.000”)

FORMATTING NUMBERS

You are ready to move on when:

LO10: You can define constants and variables, describe the difference between them and make the correct decision to use a constant or variable in your program.

LO11: You can describe the 3 main data types: integer, string and double. You can also correctly declare variables and constants with the correct data type.

LO12: You can define disposable, local and global variables/constants and describe the difference between them. You can also correctly decide whether each variable/constant should be disposable, local or global .

LEARNING OUTCOMES

LO13: You can correctly name and assign a value to a constant. You can correctly name and assign a value to a variable in the correct location within your code (remember, the order of your code matters).

LO14: You can describe what ‘Option Explicit’ is used for and why it is useful.

LO15: You can structure code correctly as well as include meaningful comments.

LO16: You can assign a control, cell, range or variable a formatted number using specific number of decimal places as currency, a percentage or a number.

You will practice these LOs in the lab

LEARNING OUTCOMES

THE END

top related