Vba Class Level 1


Published on

Level 1 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 Class Level 1

  1. 1. Visual Basic Applications (VBA) Level I By Ben Miu
  2. 2. What is Excel VBA?• VBA is a MS Office based programming language modeled after Visual Basic 6.0• Prior to VBA, automation in Excel was done with XLMMacros which lacked programming functionality• Visual Basic evolved from BASIC, getting rid of the idea of structural programming• Excel VBA is the end all of advanced Excel
  3. 3. Imagine …• Many in AIMCo is doing manual tedious tasks of cutting and pasting spreadsheets• Example: John is taking a file from a folder and creating a file folder then copying the file using Windows Explorer• Example: Jim is manually drawing a line between two charts• Example: Kim is manually cutting and pasting numbers from one spreadsheet to another• Example: Simon is grabbing prices from a website on a daily basis and putting it into a spreadsheet• What do all of these examples have in common?
  4. 4. Automation is the Answer• VBA can copy files from a folder and put it into another folder. It can create files, delete directories• VBA can draw lines between two charts and the code written can set business rules as to why you would do that• VBA can cut and paste numbers without you even having to switch sheets• VBA can access websites and grab information
  5. 5. Simply put, what can be imagined can be achieved with automation
  6. 6. Using the Macro Recorder• Macro recorder is included in Excel. It is the most basic way of learning VBA and it’s where it all starts…• Lab 1: Use the macro recorder to put the word “Ben” into Range A1. Examine the code, what do you see?
  7. 7. Advantages/Disadvantages of the Macro RecorderAdvantage:- Macro recorder has the ability to type code foryou without you knowing ‘the code’- It can simplify your tasks if you are simplycutting and pasting the same cell everydayDisadvantage:- Lacks clear business logic abilities- Code is highly inefficient
  8. 8. The VBA Code Screen• Alt-F11 opens up the code screen, or you can use the Developer Tab• Macros may be disabled in Excel so you may need to tweak security settings, always save your files as .XLSM so you don’t lose your code• Code is inserted into modules. Each time you use the recorder, a new module is created. Not necessarily the best approach
  9. 9. Code goes there
  10. 10. Recorder Code, before and after
  11. 11. After …
  12. 12. What happened?• Macro recorder had to select each cell first and then used ambiguous activecell reference to change cell value• The R1C1 doesn’t state anything about which cell you are changing and is not intuitive to people reading the code• Code can be extremely long if you have to use the recorder for many entries
  13. 13. Why?Workbooks(“Daily Risk.xlsm”).Sheets(“Sheet1”).Range(“A1”).Value = “Ben” ValueWorkbooks Sheet ReferenceReference Range Reference Rewrite your lab using this syntax
  14. 14. Play and stopbutton The VBE Interface Code inserted into a Subroutine Modules hold code Intermediates Window / Debug Window
  15. 15. What is a variable?• Variables store information into the computers memory for easy access• Variables can contain text, numbers, dates, arrays, objects• Example of creating a variableDim TotalAmount as DoubleChoose a proper name for your variables
  16. 16. Types of Variables• String – Text Only• Integer - -32768 to 32767 (Whole numbers only, no decimals)• Long - -2,147,483,684 to 2,147,483,684(Whole numbers only, no decimals)• Boolean – True or False• Double – Numbers with decimals• Any variables not declared with a dim statement are assigned as Variant
  17. 17. Sample CodeSub Test() Declare variableDim TotalAmount as Double Assign variableTotalAmount = 100.00Range(“A5”).Value = TotalAmount ProcedureEnd Sub ()
  18. 18. If-Then-Else• If-Then-Else is your most commonly used decision tree statement• If Condition Then If statements must Code goes here always have a End If End If If Condition Then Code goes here Else statement executes code if Else condition is not met Code goes here End If
  19. 19. Range vs. Cell• Range(“A5”).Value = 100• Cells(1,5).Value = 100 Both statements do the same thing. The Cells statement is useful if you know the row and column index number
  20. 20. String Concatenation• You already know how to Dim a variable and assign a value to itDim SanaActivity as StringDim ActivityString as StringActivityString = “Skiing”SanaActivity = “Sana enjoys “ & Activitystring & “very much”
  21. 21. Indenting your code and commenting your code • Always important to indent your code • Use the ‘ to comment your code Good CodeDim TotalAmount as Double ‘Creates variablesTotalAmount = 100 Dim TotalAmount as DoubleIf Range(“A5”).Value = 200 Then ‘Assigns variablesRange(“A5”).Value = TotalAmount TotalAmount = 100ElseRange(“A5”).Value = “No” ‘Assigns a proper value to the cellEnd If If Range(“A5”).Value = 200 Then Range(“A5”).Value = TotalAmount Else Bad Code Range(“A5”).Value = “No” End If
  22. 22. Lab 2 – Writing your first programSub Test() Try experimenting with the CashAmount variable byDim CashAmount as Double typing in:CashAmount = 100 CashAmount = (100 * 2) + 40If Range(“A1”).Value > 100 Then Msgbox(“Less than 100”)ElseIf Range(“A1”).Value < 100 Then Msgbox(“Less than 100”)Else Msgbox(“Not a number”)End If What happens if you type thisEnd Sub in as the variable: CashAmount = (100 * 2) + “JERRYYANG!”
  23. 23. For Next Loop• This type of loop is if you know how many iterations you need to go through• Counter variables are used to assist the For Next Loop in moving between cells• What is a counter variable?• Counter variable is a variable which does nothing other than keep count and holds a simple integer value• Example: Dim I as Integer I=0To increment a counter variable (not used in for next loops generally), youcommonly use this notationI=I+1
  24. 24. For Next Loop continued…• Dim I as Integer What does this code do? I=0 For I = 1 to 5 Range(“A” & i).value = “Jerry” Next
  25. 25. Do While Loop• This kind of loop is used if you are not sure how many iterations you need to go through• It is used ‘while’ a condition is met. Once the condition is met, the loop kicks you out• Commonly used is with a While/Wend loop moving through ranges/cells
  26. 26. Do While Loop ExampleDim I as Integeri=1Do While Range(“A” & I ).value = “Jerry” I=I+1 Msgbox(“Yang”)Wend
  27. 27. Do Loop – Beware this one• This loop is used if you do not want to put a condition into the loop but want to put a “Exit Do” into the Do Loop• This loop is useful if you want a If-Then-Else statement to handle the exiting of the loop• Beware this loop, as this one causes a infinite loop where there is no ending (unless you ESC out of the program)
  28. 28. Do Loop ExampleDim TotalAmount as Double Do you see a problem with this code?TotalAmount = 100Do Msgbox(“TotalAmount”)Loop
  29. 29. Do Loop Proper ExampleDim TotalAmount as DoubleDim I as IntegerTotalAmount = 100I=0Do I=I+1 Msgbox(“OK”) New form of If statement Doesn’t require End If If I = 5 Then Exit DoLoop Exit Do statement throws you out of the loop
  30. 30. Lab 3 – Lots of LoopsDim TotalAmount as DoubleDim I as IntegerDim SecretaryNameSecretaryName = “Sana Farrukh”TotalAmount = 100I=0Do While TotalAmount <> 0 I=I+1 TotalAmount = TotalAmount - 1 Range(“A” & i).Value = TotalAmountLoopFor j = 100 to 1 Step -1 Range(“B” & j).Value = SecretaryNameNextI = 100Do Range(“C” & i).Value = “Our Secretary name is “ & SecretaryName I=I–1 If I = 1 Then Exit DoLoop
  31. 31. Debugging and Error Trapping• As you can see, if you mistype something, you get a Debug error message which will highlight the code that went badIe.Dim SecretaryName as StringSecretaryName = 33Error is Type Mismatch
  32. 32. Debugging and Error Trapping 2• Putting stops in code. Click on the line to the left
  33. 33. Code StopsHere
  34. 34. Using Debug.Print• Sometimes you want to find out the value of a variable as you run through your code• You don’t necessarily want to stop your code as with the prior example of the RED dot• So you use the Debug.Print to put the contents of a variable in the debug window• Useful in loops where you want to see what the loop is doing to a variable or cell
  35. 35. Debug.Print statement insertedCan you think of where the value of“a.value”Will go to? Perhaps here?
  36. 36. Do you see a problem with this if you are trying to deal with all AIMCo Employees?Dim AIMCOEmployeeLeo as StringDim AIMCO EmployeeJagdeep as StringDim AIMCO EmployeeRyan as StringAIMCOEmployeeLeo = “Leo”AIMCOEmployeeJagdeep = “Jagdeep”AIMCOEmployeeRyan = “Ryan”
  37. 37. Perhaps an array helpsDim AIMCOEmployee(250) as StringAIMCOEmployee(1) = “Leo”AIMCOEmployee(2) = “Jagdeep”AIMCOEmployee(3) = “Ryan”
  38. 38. Arrays• An array is a variable which contain several values in itself and centralizes data contained• To create an array you;Dim AIMCOEmployees(250) as StringAIMCOEmployees(1) = “Sana”AIMCOEmployees(2) = “Grant”AIMCOEmployees(3) = “Ryan”And so on…
  39. 39. Lab 4• Put the following code into Excel VBA. What happens?Dim RiskEmployees(3) as StringDim I as IntegerDim j as Integer Nested loop. Wow!I=0J=0RiskEmployees(1) = “Ryan”RiskEmployees(2) = “Grant”RiskEmployees(3) = “John”For I = 1 to 10 Range(“A” & i).Select For j = 1 to 3 If Range(“A” & i).Value = RiskEmployees(j) Then Msgbox(“Great”) NextNext
  40. 40. Summary• Macro Recorder• Creating Variables• If Then Else Loops• Do While Loops• Do Loops• Debugging and error trapping• Arrays
  41. 41. Thanks
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.