SlideShare une entreprise Scribd logo
1  sur  41
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 Recorder
Advantage:
- Macro recorder has the ability to type code for
you without you knowing ‘the code’
- It can simplify your tasks if you are simply
cutting and pasting the same cell everyday
Disadvantage:
- 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”




                                                                    Value
Workbooks                  Sheet Reference
Reference                                     Range Reference



         Rewrite your lab using this syntax
Play and stop
button               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 variable
Dim TotalAmount as Double

Choose 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 Code
Sub Test()                             Declare variable


Dim TotalAmount as Double
                                  Assign variable
TotalAmount = 100.00

Range(“A5”).Value = TotalAmount      Procedure




End 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 it

Dim SanaActivity as String
Dim ActivityString as String

ActivityString = “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 Code

Dim TotalAmount as Double         ‘Creates variables
TotalAmount = 100                 Dim TotalAmount as Double

If Range(“A5”).Value = 200 Then   ‘Assigns variables
Range(“A5”).Value = TotalAmount   TotalAmount = 100
Else
Range(“A5”).Value = “No”          ‘Assigns a proper value to the cell
End 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 program
Sub Test()                            Try experimenting with the
                                      CashAmount variable by
Dim CashAmount as Double              typing in:

CashAmount = 100                      CashAmount = (100 * 2) + 40

If 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 this
End 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=0

To increment a counter variable (not used in for next loops generally), you
commonly use this notation
I=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 Example
Dim I as Integer
i=1

Do 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 Example
Dim TotalAmount as Double      Do you see a problem
                               with this code?
TotalAmount = 100

Do
       Msgbox(“TotalAmount”)
Loop
Do Loop Proper Example
Dim TotalAmount as Double
Dim I as Integer

TotalAmount = 100
I=0

Do
       I=I+1
       Msgbox(“OK”)                         New form of If statement
                                            Doesn’t require End If
       If I = 5 Then Exit Do
Loop
                   Exit Do statement throws you out of the loop
Lab 3 – Lots of Loops
Dim TotalAmount as Double
Dim I as Integer
Dim SecretaryName
SecretaryName = “Sana Farrukh”
TotalAmount = 100
I=0
Do While TotalAmount <> 0
                I=I+1
                TotalAmount = TotalAmount - 1
                Range(“A” & i).Value = TotalAmount
Loop

For j = 100 to 1 Step -1
                   Range(“B” & j).Value = SecretaryName
Next

I = 100

Do
                 Range(“C” & i).Value = “Our Secretary name is “ & SecretaryName
                 I=I–1
                 If I = 1 Then Exit Do
Loop
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 bad
Ie.

Dim SecretaryName as String
SecretaryName = 33
Error is Type Mismatch
Debugging and Error Trapping 2
• Putting stops in code. Click on the line to the
  left
Code Stops
Here
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 inserted
Can 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 String
Dim AIMCO EmployeeJagdeep as String
Dim AIMCO EmployeeRyan as String

AIMCOEmployeeLeo = “Leo”
AIMCOEmployeeJagdeep = “Jagdeep”
AIMCOEmployeeRyan = “Ryan”
Perhaps an array helps
Dim AIMCOEmployee(250) as String

AIMCOEmployee(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 String

AIMCOEmployees(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 String
Dim I as Integer
Dim j as Integer                          Nested loop. Wow!
I=0
J=0
RiskEmployees(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”)
              Next
Next
Summary
•   Macro Recorder
•   Creating Variables
•   If Then Else Loops
•   Do While Loops
•   Do Loops
•   Debugging and error trapping
•   Arrays
Thanks

Contenu connexe

Tendances

Intro to Excel VBA Programming
Intro to Excel VBA ProgrammingIntro to Excel VBA Programming
Intro to Excel VBA Programmingiveytechnologyclub
 
E learning excel vba programming lesson 2
E learning excel vba programming  lesson 2E learning excel vba programming  lesson 2
E learning excel vba programming lesson 2Vijay Perepa
 
AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2Dan D'Urso
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1Vijay Perepa
 
VBA Classes from Chandoo.org - Course Brochure
VBA Classes from Chandoo.org - Course BrochureVBA Classes from Chandoo.org - Course Brochure
VBA Classes from Chandoo.org - Course Brochurer1c1
 
How to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzalHow to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzal1995786
 
Visual Basics for Application
Visual Basics for Application Visual Basics for Application
Visual Basics for Application Raghu nath
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1guest38bf
 
Useful macros and functions for excel
Useful macros and functions for excelUseful macros and functions for excel
Useful macros and functions for excelNihar Ranjan Paital
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Blue Elephant Consulting
 
IOS Swift Language 3rd tutorial
IOS Swift Language 3rd tutorialIOS Swift Language 3rd tutorial
IOS Swift Language 3rd tutorialHassan A-j
 

Tendances (20)

Intro to Excel VBA Programming
Intro to Excel VBA ProgrammingIntro to Excel VBA Programming
Intro to Excel VBA Programming
 
Vba introduction
Vba introductionVba introduction
Vba introduction
 
E learning excel vba programming lesson 2
E learning excel vba programming  lesson 2E learning excel vba programming  lesson 2
E learning excel vba programming lesson 2
 
Vba
Vba Vba
Vba
 
AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2
 
Using Vba Excel
Using Vba ExcelUsing Vba Excel
Using Vba Excel
 
Vba Class Level 3
Vba Class Level 3Vba Class Level 3
Vba Class Level 3
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1
 
VBA Classes from Chandoo.org - Course Brochure
VBA Classes from Chandoo.org - Course BrochureVBA Classes from Chandoo.org - Course Brochure
VBA Classes from Chandoo.org - Course Brochure
 
Excel vba
Excel vbaExcel vba
Excel vba
 
VBA
VBAVBA
VBA
 
How to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzalHow to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzal
 
MACROS excel
MACROS excelMACROS excel
MACROS excel
 
Visual Basics for Application
Visual Basics for Application Visual Basics for Application
Visual Basics for Application
 
Vba part 1
Vba part 1Vba part 1
Vba part 1
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
 
Useful macros and functions for excel
Useful macros and functions for excelUseful macros and functions for excel
Useful macros and functions for excel
 
Excel macro
Excel macroExcel macro
Excel macro
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2
 
IOS Swift Language 3rd tutorial
IOS Swift Language 3rd tutorialIOS Swift Language 3rd tutorial
IOS Swift Language 3rd tutorial
 

Similaire à Vba Class Level 1

A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of Cjeremyrand
 
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA LearningExcel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA LearningPrantikMaity6
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statementsVladislav Hadzhiyski
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and SelectionAhmed Nobi
 
Learn VBA Training & Advance Excel Courses in Delhi
Learn VBA Training & Advance Excel Courses in DelhiLearn VBA Training & Advance Excel Courses in Delhi
Learn VBA Training & Advance Excel Courses in Delhiibinstitute0
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2Yo Halb
 
Programming with C++
Programming with C++Programming with C++
Programming with C++ssuser802d47
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection StatementsSzeChingChen
 

Similaire à Vba Class Level 1 (20)

A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
 
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA LearningExcel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and Selection
 
Learn VBA Training & Advance Excel Courses in Delhi
Learn VBA Training & Advance Excel Courses in DelhiLearn VBA Training & Advance Excel Courses in Delhi
Learn VBA Training & Advance Excel Courses in Delhi
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Pythonintro
PythonintroPythonintro
Pythonintro
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Vbscript
VbscriptVbscript
Vbscript
 
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
 
Arrays
ArraysArrays
Arrays
 
Programming with C++
Programming with C++Programming with C++
Programming with C++
 
Python Basics
Python BasicsPython Basics
Python Basics
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
Vb (2)
Vb (2)Vb (2)
Vb (2)
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
 
CPP10 - Debugging
CPP10 - DebuggingCPP10 - Debugging
CPP10 - Debugging
 

Vba Class Level 1

  • 1. Visual Basic Applications (VBA) Level I By Ben Miu
  • 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. 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. 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. Simply put, what can be imagined can be achieved with automation
  • 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. Advantages/Disadvantages of the Macro Recorder Advantage: - Macro recorder has the ability to type code for you without you knowing ‘the code’ - It can simplify your tasks if you are simply cutting and pasting the same cell everyday Disadvantage: - Lacks clear business logic abilities - Code is highly inefficient
  • 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
  • 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. Why? Workbooks(“Daily Risk.xlsm”).Sheets(“Sheet1”).Range(“A1”).Value = “Ben” Value Workbooks Sheet Reference Reference Range Reference Rewrite your lab using this syntax
  • 14. Play and stop button The VBE Interface Code inserted into a Subroutine Modules hold code Intermediates Window / Debug Window
  • 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 variable Dim TotalAmount as Double Choose a proper name for your variables
  • 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. Sample Code Sub Test() Declare variable Dim TotalAmount as Double Assign variable TotalAmount = 100.00 Range(“A5”).Value = TotalAmount Procedure End Sub ()
  • 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. 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. String Concatenation • You already know how to Dim a variable and assign a value to it Dim SanaActivity as String Dim ActivityString as String ActivityString = “Skiing” SanaActivity = “Sana enjoys “ & Activitystring & “ very much”
  • 21. Indenting your code and commenting your code • Always important to indent your code • Use the ‘ to comment your code Good Code Dim TotalAmount as Double ‘Creates variables TotalAmount = 100 Dim TotalAmount as Double If Range(“A5”).Value = 200 Then ‘Assigns variables Range(“A5”).Value = TotalAmount TotalAmount = 100 Else Range(“A5”).Value = “No” ‘Assigns a proper value to the cell End If If Range(“A5”).Value = 200 Then Range(“A5”).Value = TotalAmount Else Bad Code Range(“A5”).Value = “No” End If
  • 22. Lab 2 – Writing your first program Sub Test() Try experimenting with the CashAmount variable by Dim CashAmount as Double typing in: CashAmount = 100 CashAmount = (100 * 2) + 40 If 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 this End Sub in as the variable: CashAmount = (100 * 2) + “JERRYYANG!”
  • 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=0 To increment a counter variable (not used in for next loops generally), you commonly use this notation I=I+1
  • 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. 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. Do While Loop Example Dim I as Integer i=1 Do While Range(“A” & I ).value = “Jerry” I=I+1 Msgbox(“Yang”) Wend
  • 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. Do Loop Example Dim TotalAmount as Double Do you see a problem with this code? TotalAmount = 100 Do Msgbox(“TotalAmount”) Loop
  • 29. Do Loop Proper Example Dim TotalAmount as Double Dim I as Integer TotalAmount = 100 I=0 Do I=I+1 Msgbox(“OK”) New form of If statement Doesn’t require End If If I = 5 Then Exit Do Loop Exit Do statement throws you out of the loop
  • 30. Lab 3 – Lots of Loops Dim TotalAmount as Double Dim I as Integer Dim SecretaryName SecretaryName = “Sana Farrukh” TotalAmount = 100 I=0 Do While TotalAmount <> 0 I=I+1 TotalAmount = TotalAmount - 1 Range(“A” & i).Value = TotalAmount Loop For j = 100 to 1 Step -1 Range(“B” & j).Value = SecretaryName Next I = 100 Do Range(“C” & i).Value = “Our Secretary name is “ & SecretaryName I=I–1 If I = 1 Then Exit Do Loop
  • 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 bad Ie. Dim SecretaryName as String SecretaryName = 33 Error is Type Mismatch
  • 32. Debugging and Error Trapping 2 • Putting stops in code. Click on the line to the left
  • 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. Debug.Print statement inserted Can you think of where the value of “a.value” Will go to? Perhaps here?
  • 36. Do you see a problem with this if you are trying to deal with all AIMCo Employees? Dim AIMCOEmployeeLeo as String Dim AIMCO EmployeeJagdeep as String Dim AIMCO EmployeeRyan as String AIMCOEmployeeLeo = “Leo” AIMCOEmployeeJagdeep = “Jagdeep” AIMCOEmployeeRyan = “Ryan”
  • 37. Perhaps an array helps Dim AIMCOEmployee(250) as String AIMCOEmployee(1) = “Leo” AIMCOEmployee(2) = “Jagdeep” AIMCOEmployee(3) = “Ryan”
  • 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 String AIMCOEmployees(1) = “Sana” AIMCOEmployees(2) = “Grant” AIMCOEmployees(3) = “Ryan” And so on…
  • 39. Lab 4 • Put the following code into Excel VBA. What happens? Dim RiskEmployees(3) as String Dim I as Integer Dim j as Integer Nested loop. Wow! I=0 J=0 RiskEmployees(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”) Next Next
  • 40. Summary • Macro Recorder • Creating Variables • If Then Else Loops • Do While Loops • Do Loops • Debugging and error trapping • Arrays