VBA 101: BACK TO BASICS - sumproduct-4634.kxcdn.com...What is VBA? •Visual Basic for Applications...
Transcript of VBA 101: BACK TO BASICS - sumproduct-4634.kxcdn.com...What is VBA? •Visual Basic for Applications...
VBA 101: BACK TO BASICSTim Heng
Director at SumProduct, Excel MVPwww.sumproduct.com | @timaheng | https://www.linkedin.com/in/timheng/
1
Session outline:
• Recording and adapting macros
• Understand the high-level do’s and don’ts of working in VBA
• Learning how to use simple loops and conditions
• What to consider before you copy and paste code from forums and websites.
2
Recording and adapting macrosWhat is VBA and how do we get started?
What is VBA?
• Visual Basic for Applications
• Relatively simple coding language used in Excel and other Office applications
• Object-based programming
• Objects (nouns), properties (adjectives) and methods (verbs)
• Object.Property = X
• NotMyDog.Coat = TooHairy
• Object.Method
• VeryHungryCaterpillar.Eats OneApple, TwoPears, ThreePlums
4
What is VBA?
• Objects (nouns), properties (adjectives) and methods (verbs)
• Range(“A1:C5”).Font.Name = “Arial”
Object Properties
• Selection.Copy
Object Method
5
Recording Macros
Easy to start recording – click and go
Long form: View -> Macros -> Record Macro
6
Common characteristics of recorded macros
Task VBA recording Recommended adaptation
Select a cell Range(“A1”).Select Range(“CellName”).Select
Select the next sheet ActiveSheet.Next.Select Sheets(“SheetName”).Select
Copy a range Range("C6").SelectSelection.Copy
Range(“C6”).Copy
Paste into a range Range("D6").SelectActiveSheet.Paste
orSelection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _False, Transpose:=False
Range(“D6”).PasteSpecial xlPasteAll
7
Common characteristics of recorded macros
Task VBA recording Recommended adaptation
Change the font to Arial With Selection.Font.Name = "Arial".Size = 22.Strikethrough = False.Superscript = False.Subscript = False.OutlineFont = False.Shadow = False.Underline = xlUnderlineStyleNone.ThemeColor = xlThemeColorLight1.TintAndShade = 0.ThemeFont = xlThemeFontNone
End With
Range(“A1”).Font.Name = “Arial”
8
Using variables
• Variables allow you to store values while your code is run
• Useful for a range of purposes:
• Tracking the number of times a loop is run
• Storing a value temporarily while you make changes to the spreadsheet
• Best practice to declare (dimension) the variable before using it
• Dim VariableName as String
• Dim LoopCounter as Integer
9
High level do’s and don’ts
Things to avoid
• Don’t use cell references (e.g. “C5”)
• Use Named Ranges instead of cell references (e.g. “Macro_Check”)
• Remove unnecessary / unintended macro steps
• Try to avoid using .Copy (minimise interaction with the clipboard)
11
Things to do
• Instead of copying and pasting, use X = Y type code instead:
• Range(“Macro_Paste”).Value = Range(“Macro_Copy”).Value
• Range(“Macro_Paste”).Formula = Range(“Macro_Copy”).Formula
• Combine Select / Selection steps into one
• Range(“A1”).Select // Selection.Copy => Range(“A1”).Copy
12
Things to do
• Pay attention to sheet context
• Range(“A1”) <> Sheets(“Sheet1”).Range(“A1”)
• Use comments
• ‘Single inverted comma at the front of a line
• Can use the Comment Block tool in the Edit toolbar
• Option Explicit
• Forces variables to be declared
• Helps identify cases where variable names are misused
13
Simple loops and conditions
If… Then… Else
• Allows for conditional rules to be checked
• Syntax:
If <true/false condition> Then
<do something here>
Else
<do something else>
End If
15
Do… Loop
• Repeats a set of code a variable number of times
• Syntax:
Do
<do something here>
Loop
• Optional formats:
• Do While <X is true> check a condition and perform loop if true
• Loop while <X is true> loop once then check and perform loop again if true
16
For… Next
• Repeats a set of code a fixed number of times
• Syntax:
For x = 1 to 10
<do something here>
Next x
• x is an integer variable – a range of different items can be used
• The value x increments each time it loops through the code
• Can use some other formats too: For Each Sheet in Sheets()
17
Copying and pasting code from onlineHow to choose between A or B
How to pick good code
• Does it follow good coding practice?• Is it well laid out using indenting and comments?
• Does it used named ranges instead of direct cell references?
• Are variables declared explicitly?
• Is it well regarded by the community? (Likes, upvotes, MVP blogs, etc.)
• Most importantly – can you follow what it’s doing?
19
Questions?
VBA 101: Back to BasicsFeedback:
CBA Non-CBA
Downloads: https://www.sumproduct.com/Excel-Summit-2019/Excel-Summit-Sydney-2019
www.sumproduct.com | @timaheng | https://www.linkedin.com/in/timheng/
Thursday’s sessions
22
What’s New in Excel8:30 – 9:55
Rolling Budgets and Charts10:25 – 11:35 Excel 365 v Excel 2016
Dynamic Data4:00 – 5:00 Advanced Chart Tricks for the Non-Advanced User
Morning Tea and Networking Break9:55 – 10:25
Real & Unusual Needs / Uses for Excel11:40 – 12:40 Creating More Effective Charts
Lunch12:40 – 1:25
Painting to Present Your Data1:25 – 2:25 CTRL + ENTER: Start Using it Yesterday!
Excel Tips & Tricks2:30 – 3:30 Testing Models
Afternoon Tea and Networking Break3:30 – 4:00
Q&A Session (What’s on Your Excel Wish List?)5:00 – 5:30
Room A Room B
Friday’s sessions
23
Microsoft 365: Unlocking the Power of Your Enterprise Data8:30 – 9:30
Forecasting Tips10:00 – 10:55 Time Intelligence in Power Pivot
Three Real Business Solutions Using Power BI for Excel4:00 – 5:00 PivotTables and Slicers
Morning Tea and Networking Break9:30 – 10:00
VBA 101: Back to Basics11:00 – 11:55 Assessing Client Needs
Lunch12:55 – 1:35
Real-World Case Studies Using Power BI and Power Query2:35 – 3:30 Conditional Formatting
Out of the Box Use of Well-Known Excel Functions1:35 – 2:30 Deep Dive into All Six Joins in Power Query
Afternoon Tea and Networking Break3:30 – 4:00
Q&A Session (Part 2)5:00 – 5:30
Room A Room B
Data Model in Power BI: Different Approaches12:00 – 12:55 Going from Excel to PowerPoint