Vba Excel Level 2

41
VBA Excel Level II By Ben Miu

description

Level 2 of a class which I lead at AIMCo in training investment professionals in VBA programming

Transcript of Vba Excel Level 2

Page 1: Vba Excel Level 2

VBA Excel Level II

By Ben Miu

Page 2: Vba Excel Level 2

What do we know?

• Macro Recorder• Basic Variables• If Then Else• Loops• Debugging and error trapping• ArraysNow, how do you take your coding to a new level?

Page 3: Vba Excel Level 2

Review Lab• Type the following code into Excel VBA

Dim AIMCOEmployeeNames(2) as StringAIMCOEmployeeNames(1) = “Jerry”AIMCOEmployeeNames(2) = “Yang”

For I = 1 to 5If Range(“A” & i).value = AIMCOEmployeeNames(1) Then Msgbox (“Found

Jerry”)

If Range(“A” & i).value = AIMCOEmployeeNames(2) Then Msgbox(“Found Yang”)

Next i

Page 4: Vba Excel Level 2

String Operations

• InStr function – Tells you if a particular string is contained in a string. The value you will return is the location of the string in question, 0 returned if string not found

• Mid function – Tells you if a particular string in any particular order

If InStr(Range(“A5”).Value, “Jerry”) > 0 Then

If Mid(Range(“A5”).Value,1,1) = “J” Then

Page 5: Vba Excel Level 2

Dilemma

• Say you have the following table

Ben Miu - $100Ryan Miu - $200Jessica Wang - $300Guan Miu - $500

You want to add $100 to each person who has the last name “Miu”. What code could you write?

Page 6: Vba Excel Level 2

Solution

• You could put the results in column C

Ben Miu - $100 $200Ryan Miu - $200 $300Jessica Wang - $300Guan Miu - $500 $600

For I = 1 to 4If InStr(Range(“A” & i).Value, “Miu) > 0 Then _

Range(“C” & i).Value = Range(“B” & i).Value + 100Next

Quick tip, if you are using a single If statement with no Else, you can use the following notation below

Do you see an issue with the For loop here? It assumes your list has only 4 people but what if you had 1000 names in column A, would you simply count 1000 rows ahead of time and put it into your loop

Page 7: Vba Excel Level 2

Range ObjectAssetsAccounts Receivable 200Cash 100Investments 300Property 100Equipment 200

Dim a as RangeSet a = Range(“A1”)

While a <> “”a.offset(0,2).value = a.offset(0,1).value + 100Set a = a.offset(1,0)

Wend

Range objects allow you to treat cells as if they were individual variables

This code executes as long as there is no blank in Column A

Page 8: Vba Excel Level 2

Offset / Range / While

• Offset statement has a row and column section. So if you are in Range(“A1”) and you offset 1 to the right then it is Offset(0,1)

• The Set statement sets the range to a particular cell and allows you to move about Excel treating cells as Range values

• While/Wend loop is equivalent to the Do While Loop as discussed in Level 1

Page 9: Vba Excel Level 2

Lab 1 – Dealing with a real problem

Put this into ExcelMr. Bubley 24Mr. Suleyman 25Mr. Marsden 25Mrs. Osborne 26Mrs. Mao 27Mr. Mao 28

Michael Baker has asked you to determine if a particular name is a MALE name or a FEMALE name and provide him with the results.

Well, a name with MR in it is a Male name and a name with MRS in it is a FEMALE name

Page 10: Vba Excel Level 2

Lab 1 – Write this codeDim a as RangeSet a = Range(“A1”)

While a <> “”If InStr(a.value, “Mr.”) > 0 Then a.offset(0,2).value = “Male”Elsea.offset(0,2).value = “Female”End If

Set a = a.offset(1,0)Wend

What happens if you change the a.offset line to a.offset(0,3) instead?

Page 11: Vba Excel Level 2

Subroutines and Functions

• So far, we have only used one subroutine (ie. the sub where you put your code)

• What if you want to stop copying the same code over and over again?

• Subroutines perform a procedure whereas functions provide a piece of information back to the calling sub.

Page 12: Vba Excel Level 2

ExampleDim a as RangeSet a = Range(“A1”)

While a <> “”If a.value = “Jerry” Then

msgbox(“Way”)Msgbox(“To”)Msgbox(“Go”)Msgbox(a.value)

ElseIf a.value = “Grant” Thenmsgbox(“Way”)Msgbox(“to”)Msgbox(“Go”)Msgbox(a.value)

ElseMsgbox(“Way”)Msgbox(“to”)Msgbox(“Go”)Msgbox(a.value)

End If

Set a = a.offset(1,0)Wend

Getting a bit repetitive don’t you think?

Page 13: Vba Excel Level 2

How About?Sub Main()Dim a as RangeSet a = Range(“A1”)

While a <> “”If a.value = “Jerry” ThenCall WayToGo(a.value)ElseIf a.value = “Grant” ThenCall WayToGo(a.value)Else

Call WayToGo(a.value)

End If

Set a = a.offset(1,0)WendEnd Sub()

Sub WayToGo(ByVal namevalue as String)Msgbox(“Way”)Msgbox(“To”)Msgbox(‘Go”)Msgbox(namevalue)

End Sub

Call statement calls another subroutine

We are not using a Function as we are notExpecting a value to be returned

We are ‘passing’ the information in a.value into the subroutine

This approach starts to define object oriented programming

Page 14: Vba Excel Level 2

What is a Function?

• A function is used if you want to receive a piece of information back to your calling subroutine

• See next example…

Page 15: Vba Excel Level 2

Example of a FunctionSub Main()

Dim AIMCOName as StringAIMCOName = FindLastNameOf(“Jerry”)

End Sub

Function FindLastNameOf(strName) as StringIf strName = “Jerry” ThenFindLastNameOf = “Yang”ElseFindLastNameOf = “N/A”End If

End function

What will the variableAIMCOName hold?

Page 16: Vba Excel Level 2

Lab 2 – Subs/Functions and Ranges• Type in the following code to see how ranges and separate subs/functions can help

Sub Main()Dim a as RangeSet a = Range(“A1”)

While a <> “”If a.value = “Jerry” ThenCall WayToGo(a.value)ElseIf a.value = “Grant” ThenCall WayToGo(a.value)Else

Call WayToGo(a.value)

End If

Set a = a.offset(1,0)WendEnd Sub()

Sub WayToGo(ByVal namevalue as String)Msgbox(“Way”)Msgbox(“To”)Msgbox(‘Go”)Msgbox(namevalue)

End Sub

Page 17: Vba Excel Level 2

ByVal vs ByRef

Variables are passed by default ByVal unless specified otherwise

Sub Test()Call Ben(a.value)

End Sub

Sub Ben(strName)Msgbox(a.value)

End Sub

Same way to write this code is using this syntax:

Sub Test()Call Ben(a.value)

End Sub

Sub Ben(ByVal strName as String)Msgbox(a.value)

End Sub

Page 18: Vba Excel Level 2

ByVal vs ByRef

This is how to pass a variable ByRef

Sub Test()Call Ben(a.value)

End Sub

Sub Ben(ByRef strName as String)Msgbox(a.value)

End Sub

So what is the difference?

Page 19: Vba Excel Level 2

ByVal vs ByRef

• When you pass a variable into another sub or function, ByVal means you are passing the actual value

• ByRef means you are passing the variable reference therefore if any changes occur to the variable in the new sub, it is changed in the originating variable

• This isn’t really used in day to day VBA programming as ByVal is usually sufficient so this won’t be covered in a lab

Page 20: Vba Excel Level 2

Dictionaries and Collections

• Arrays have an inherit problem of you having to know beforehand how many data values you have

• Ie.

Dim AIMCoEmployees(250) as StringAIMCOEmployees(1) = “Ryan”

What if you didn’t knowAIMCO had 250 employees?

Page 21: Vba Excel Level 2

Dictionaries and Collections

• What if you wanted to store more information and not just employee names?

• What if you wanted to store the employee name and also their employee number?

Dim AIMCOEmployees(250) as StringDim AIMCOEmployeeNumber(250) as IntegerAIMCOEmployees(1) = “Ryan”AIMCOEmployeeNumber(1) = 14000

Page 22: Vba Excel Level 2

Dictionaries and Collections

• Collections and Dictionaries are the foundation blocks of building a robust application (Daily Risk covered in level 3)

• Collections/Dictionaries is basically a phone book with a Key and a Item. See below:

“Jerry Yang”, 555-5555

Page 23: Vba Excel Level 2

What is the difference between dictionary and collection

The same thing essentially. Only difference is the dictionary object is more user friendly and robust as you can check if a KEY exists without using On Error statements. You do however have to add a library reference for the dictionary object

Page 24: Vba Excel Level 2

Library Reference

• Library references allow you to access the methods and functions of other Windows applications

• It allows you to control Powerpoint, Access and Word all from within Excel. It also allows you to control Outlook

• For the purposes of this class, we will only show you how to add a library reference and not go deeper into this topic

Page 25: Vba Excel Level 2

Add a Library Reference

• Add a library reference to MS Scripting RunTime. In the VBA code window, click on Tools and then go to References. Find the entry that says Microsoft Scripting Runtime and then click on the checkbox and click OK.

Page 26: Vba Excel Level 2

Adding a Dictionary Reference

• To add a dictionary reference, you use the following syntax

Dim dictJerrysBloodPressure as New Dictionary

dictJerrysBloodPressure.Add Key, ItemSoDictjerrysBloodPressure.Add “Morning”, “120/80”

Page 27: Vba Excel Level 2

Referencing a dictionary reference

• To reference a dictionary reference you use the syntax below

dictjerryBloodPressure.Item(Key)

Example:Bloodpressurevalue = dictJerryBloodPressure.Item(“Morning”)

Page 28: Vba Excel Level 2

Automation Concepts: Xref Tables

• Cross reference tables are the foundation of automation theory. Dictionary objects work with Xref tables to create robust VBA programs

• For example, say you are dealing with two systems, Eagle and FMC. A Eagle security might be called “MICROSOFT” but in FMC it might be called “MSFT”, because of these differences, you setup a Xref table beforehand and then you use the dictionary to reference it

• Xref tables will be covered more in Level 3 when the Case studies Daily Risk will be presented

Page 29: Vba Excel Level 2

Lab 3Enter the following code into Excel (remember to make a library reference to the scripting runtime if you haven’t done so already)

Dim dictEmployeeID as New DictionaryDim a as Range: Set a = Range(“A1”)

While a <> “”dictEmployeeID.Add a.value, a.offset(0,1).valueSet a=a.offset(1,0)

Wend

For each key in dictEmployeeID.KeysMsgbox(dictEmployeeID.Item(Key))

Next key

Load Phase, Use Phase

Page 30: Vba Excel Level 2

Userforms

• Open up Excel and go to the VBA code screenRight click and choose Insert and then UserForm

Page 31: Vba Excel Level 2

UserformsToolbox

Page 32: Vba Excel Level 2

UserformsWhen you add a button and you drag it on the Userform, go to the buttons’ properties and call the button “btnClick” for name and for text type in “Click Me”

Page 33: Vba Excel Level 2

Userforms

• Adding a label

Text that goes into a label uses the Caption property. Call this textbox (name), lblText

Page 34: Vba Excel Level 2

Now let’s make the commandbutton work

• Double click on the CommandButton and type in this:

Private Sub btnClick_Click()Msgbox(“Hello”)

End Sub

Page 35: Vba Excel Level 2

Background notes

• When you double click on the button you will notice the following Sub was added,

• Sub btnClick_ClickThe _Click at the end represents the event. Therefore, the code executes when someone clicks on the buttonYou shouldn’t put too much code into the click event as the userform code doesn’t have the full functionality of codes in a module so you should add a new module and put a Call statement there ie.

Call Module1.Main()

Page 36: Vba Excel Level 2

What if you wanted the userform to show when the person opened up Excel?

• On the Project screen, double click on Thisworkbook. Then click on the First dropdown menu and choose Workbook and then make sure the right drop down menu says Open

Page 37: Vba Excel Level 2

Type in the following Code

UserForm1.Show()

Then when the workbook opens, your user form will show up automatically

Page 38: Vba Excel Level 2

Lab 4 – Putting it all together

Create a Userform that looks like below:

Page 39: Vba Excel Level 2

Lab 4 – Putting it all Together• For the commandbutton’s click event, have it say:Call Module1.Main()

Then create a new module and type in the following:

Sub Main()Dim dictEmployee as New DictionaryDim strName as VariantdictEmployee.Add “Jerry”, “1-800-JER-YANG”dictEmployee.Add “Guan”, “1-888-GUA-KHOO”

strName = Inputbox(“Please enter a employee name”)If dictEmployee.Exists(strName) Then msgbox(“Thanks, here is his phone number “ &

dictEmployee.Item(strName)) Else msgbox(“Person you entered does not exist”)

End Sub

Try adding more entries to the dictEmployee line if you wish

Page 40: Vba Excel Level 2

Summary

• String Operators (InStr and Mid)• Subs and Functions• ByVal vs. ByRef• Dictionaries and Collections• Ranges• UserForms• Event Handlers

Page 41: Vba Excel Level 2

Thanks