• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Vba Class Level 1
 

Vba Class Level 1

on

  • 893 views

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

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

Statistics

Views

Total Views
893
Views on SlideShare
893
Embed Views
0

Actions

Likes
1
Downloads
82
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Vba Class Level 1 Vba Class Level 1 Presentation Transcript

    • Visual Basic Applications (VBA) Level I By Ben Miu
    • 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
    • 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?
    • 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
    • Simply put, what can be imagined can be achieved with automation
    • 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?
    • 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
    • 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
    • Code goes there
    • Recorder Code, before and after
    • After …
    • 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
    • Why?Workbooks(“Daily Risk.xlsm”).Sheets(“Sheet1”).Range(“A1”).Value = “Ben” ValueWorkbooks Sheet ReferenceReference Range Reference Rewrite your lab using this syntax
    • Play and stopbutton The VBE Interface Code inserted into a Subroutine Modules hold code Intermediates Window / Debug Window
    • 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
    • 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
    • Sample CodeSub Test() Declare variableDim TotalAmount as Double Assign variableTotalAmount = 100.00Range(“A5”).Value = TotalAmount ProcedureEnd Sub ()
    • 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
    • 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
    • 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”
    • 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
    • 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!”
    • 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
    • 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
    • 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
    • Do While Loop ExampleDim I as Integeri=1Do While Range(“A” & I ).value = “Jerry” I=I+1 Msgbox(“Yang”)Wend
    • 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)
    • Do Loop ExampleDim TotalAmount as Double Do you see a problem with this code?TotalAmount = 100Do Msgbox(“TotalAmount”)Loop
    • 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
    • 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
    • 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
    • Debugging and Error Trapping 2• Putting stops in code. Click on the line to the left
    • Code StopsHere
    • 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
    • Debug.Print statement insertedCan you think of where the value of“a.value”Will go to? Perhaps here?
    • 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”
    • Perhaps an array helpsDim AIMCOEmployee(250) as StringAIMCOEmployee(1) = “Leo”AIMCOEmployee(2) = “Jagdeep”AIMCOEmployee(3) = “Ryan”
    • 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…
    • 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
    • Summary• Macro Recorder• Creating Variables• If Then Else Loops• Do While Loops• Do Loops• Debugging and error trapping• Arrays
    • Thanks