Vba Excel Level 2


Published on

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

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Vba Excel Level 2

  1. 1. VBA Excel Level II By Ben Miu
  2. 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 newlevel?
  3. 3. Review Lab• Type the following code into Excel VBADim AIMCOEmployeeNames(2) as StringAIMCOEmployeeNames(1) = “Jerry”AIMCOEmployeeNames(2) = “Yang”For I = 1 to 5 If Range(“A” & i).value = AIMCOEmployeeNames(1) Then Msgbox(“Found Jerry”) If Range(“A” & i).value = AIMCOEmployeeNames(2) ThenMsgbox(“Found Yang”)Next i
  4. 4. 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 orderIf InStr(Range(“A5”).Value, “Jerry”) > 0 ThenIf Mid(Range(“A5”).Value,1,1) = “J” Then
  5. 5. Dilemma• Say you have the following tableBen Miu - $100Ryan Miu - $200Jessica Wang - $300Guan Miu - $500You want to add $100 to each person who has thelast name “Miu”. What code could you write?
  6. 6. Solution• You could put the results in column CBen Miu - $100 $200 Quick tip, if you areRyan Miu - $200 $300 using a single IfJessica Wang - $300 statement with no Else, you can use theGuan Miu - $500 $600 following notation belowFor I = 1 to 4 If InStr(Range(“A” & i).Value, “Miu) > 0 Then _ Range(“C” & i).Value = Range(“B” & i).Value + 100Next 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
  7. 7. Range ObjectAssetsAccounts Receivable 200Cash 100Investments 300Property 100Equipment 200Dim a as Range Range objects allow you to treat cells as if theySet a = Range(“A1”) were individual variablesWhile a <> “” a.offset(0,2).value = a.offset(0,1).value + 100 This code executes as long as Set a = a.offset(1,0) there is no blank in Column AWend
  8. 8. 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
  9. 9. Lab 1 – Dealing with a real problemPut 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
  10. 10. 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” Else a.offset(0,2).value = “Female” End If What happens if you change the a.offset line Set a = a.offset(1,0) to a.offset(0,3) instead?Wend
  11. 11. 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.
  12. 12. 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” Then msgbox(“Way”) Getting a bit repetitive don’t you think? Msgbox(“to”) Msgbox(“Go”) Msgbox(a.value) Else Msgbox(“Way”) Msgbox(“to”) Msgbox(“Go”) Msgbox(a.value) End If Set a = a.offset(1,0)Wend
  13. 13. How About?Sub Main()Dim a as RangeSet a = Range(“A1”) Call statement calls another subroutineWhile a <> “” If a.value = “Jerry” Then We are not using a Function as we are not Call WayToGo(a.value) ElseIf a.value = “Grant” Then Expecting a value to be returned Call WayToGo(a.value) Else End If Call WayToGo(a.value) We are ‘passing’ the information in a.value Set a = a.offset(1,0) into the subroutineWendEnd Sub() This approach starts to define object orientedSub WayToGo(ByVal namevalue as String) Msgbox(“Way”) programming Msgbox(“To”) Msgbox(‘Go”) Msgbox(namevalue)End Sub
  14. 14. 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…
  15. 15. Example of a FunctionSub Main() Dim AIMCOName as String AIMCOName = FindLastNameOf(“Jerry”)End Sub What will the variableFunction FindLastNameOf(strName) as String AIMCOName hold? If strName = “Jerry” Then FindLastNameOf = “Yang” Else FindLastNameOf = “N/A” End IfEnd function
  16. 16. Lab 2 – Subs/Functions and Ranges• Type in the following code to see how ranges and separate subs/functions can helpSub Main()Dim a as RangeSet a = Range(“A1”)While a <> “” If a.value = “Jerry” Then Call WayToGo(a.value) ElseIf a.value = “Grant” Then Call 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
  17. 17. ByVal vs ByRefVariables are passed by Same way to write this code is using this syntax:default ByVal unlessspecified otherwise Sub Test() Call Ben(a.value) End SubSub Test() Sub Ben(ByVal strName as String) Call Ben(a.value) Msgbox(a.value)End Sub End SubSub Ben(strName) Msgbox(a.value)End Sub
  18. 18. ByVal vs ByRefThis is how to pass a variable ByRefSub Test() Call Ben(a.value)End SubSub Ben(ByRef strName as String) Msgbox(a.value)End SubSo what is the difference?
  19. 19. 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
  20. 20. Dictionaries and Collections• Arrays have an inherit problem of you having to know beforehand how many data values you have What if you didn’t know• Ie. AIMCO had 250 employees?Dim AIMCoEmployees(250) as StringAIMCOEmployees(1) = “Ryan”
  21. 21. 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
  22. 22. 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
  23. 23. What is the difference between dictionary and collectionThe same thing essentially. Only difference isthe dictionary object is more user friendly androbust as you can check if a KEY exists withoutusing On Error statements. You do howeverhave to add a library reference for the dictionaryobject
  24. 24. 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
  25. 25. 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.
  26. 26. Adding a Dictionary Reference• To add a dictionary reference, you use the following syntaxDim dictJerrysBloodPressure as New DictionarydictJerrysBloodPressure.Add Key, ItemSoDictjerrysBloodPressure.Add “Morning”, “120/80”
  27. 27. Referencing a dictionary reference• To reference a dictionary reference you use the syntax belowdictjerryBloodPressure.Item(Key)Example:Bloodpressurevalue =dictJerryBloodPressure.Item(“Morning”)
  28. 28. 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
  29. 29. Lab 3Enter the following code into Excel (remember to make a library reference tothe scripting runtime if you haven’t done so already)Dim dictEmployeeID as New DictionaryDim a as Range: Set a = Range(“A1”) Load Phase, Use PhaseWhile a <> “” dictEmployeeID.Add a.value, a.offset(0,1).value Set a=a.offset(1,0)WendFor each key in dictEmployeeID.Keys Msgbox(dictEmployeeID.Item(Key))Next key
  30. 30. Userforms • Open up Excel and go to the VBA code screenRight clickandchooseInsert andthenUserForm
  31. 31. Toolbox Userforms
  32. 32. UserformsWhen you add a button and you drag it on the Userform, go to the buttons’ propertiesand call the button “btnClick” for name and for text type in “Click Me”
  33. 33. Userforms Text that goes into a label uses the Caption property. Call this• Adding a label textbox (name), lblText
  34. 34. Now let’s make the commandbutton work• Double click on the CommandButton and type in this:Private Sub btnClick_Click() Msgbox(“Hello”)End Sub
  35. 35. 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 asthe userform code doesn’t have the full functionality ofcodes in a module so you should add a new module andput a Call statement there ie.Call Module1.Main()
  36. 36. 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
  37. 37. Type in the following CodeUserForm1.Show()Then when the workbook opens, your user formwill show up automatically
  38. 38. Lab 4 – Putting it all togetherCreate a Userform that looks like below:
  39. 39. 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 Dictionary Dim strName as Variant dictEmployee.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
  40. 40. Summary• String Operators (InStr and Mid)• Subs and Functions• ByVal vs. ByRef• Dictionaries and Collections• Ranges• UserForms• Event Handlers
  41. 41. Thanks