ISOM3230 Business Applications Programming VBA Basic
Learning Outcomes apply programming concepts to solve business problems describe the logic and flows of given programs predict the output of a program write programs with common programming practices identify and fix logical and run-time errors in programs
Outline 1. Developer Tab 16. Operator 2. Enable Macro 17. Operator Precedence 3. Trust Center 18. Sub and Function 4. VBA Editor + Module 19. Passing Value 5. Immediate Window 20. If… End If 6. Comment 21. Select Case 7. Debug.Print 22. For… Next Loop 8. MsgBox 23. Do While/Until… Loop 9. InputBox 24. Do … Loop While/ Until 10. Data Type 25. For Each… Next 11. Constant 26. Exit Do/ Exit For 12. Declaring Variable 27. Array 13. Converting Data Type 28. Object Statement 14. Option Explicit 29. Excel Environment 15. Scope of Variable Reference
Environment + Basic Developer Tab Object Variable If … End If 6-14 Environment + Basic Developer Tab 33 Obj Object Variable Enable Macro Condi. Stat. If … End If 34-37 Trust Center Select Case Iteration For … Next Loop VBA Editor + Module 38-43 Do While/Until … Loop Immediate Window Do … Loop While/ Until Comment, _, and Main For Each … Next In/output Debug.Print 15-17 Exit Do/ Exit For MsgBox Array Array InputBox 44-49 Option Base Variable Data Type 18-23 Array Initialization Constant Redim + Preserve Declare & Assign Lbound + Ubound Converting Data Type Dynamic Array Option Explicit Scope of Variable 50-56 Object Statement Operator Operator 57 Excel Environment 24-28 Operator Precedence Ref. Color Constant 58-64 Application.InputBox Method Sub and Function 29-32 Passing Value Monitor a Variable
End
Developer Tab
Enable Macro
Trust Center (1) 046 8
Trust Center (2) 046
VBA Editor + Module Alt+F11 003
Immediate Window Press Ctrl+G to open the Immediate Window 044
Use of Immediate Window (1) Tips 1 You may use Immediate Window to execute statements. For example, after typing "Worksheets.Add" and then press Enter, a new worksheet will be created. 044
Use of Immediate Window (2) Tips 2 You may use Immediate Window to show the result value of a variable or expression. Type "? Expression" and press Enter, then the window will show the result of the expression 044
Comment, _, and Main Subroutine - A new VBA program MUST BE stored in a NEW subroutine (or known as Main Subroutine) which is created by programmers - The Name of the subroutine MUST BE a unique and valid name 008 Remarks: ’ and Rem are used to insert comments into a program _ is used to indicate that the current statement is not yet ended and the next line is part of the current statement The Naming Rules in VBA are the same as VB
Debug.Print 044
MsgBox 022 Remark: Messagebox.Show() is not available in VBA
InputBox InputBox(Prompt, Title, Default ) Remark: OK returns a String 023 Remark: OK returns a String Cancel returns Nothing
Data Type DataType Default Value Boolean False Integer Double Date Double Date 12:00:00 AM December 30, 1899 String “” Variant Empty Remark: Variant is similar to the Object data type in VB
Constant Declaring a constant _ is used here 008
Declaring Variable and Assigning Value Must be separated 004
Converting Data Type Remarks: Build-in Constant Remarks: All of the following are available in VBA CBool() CDbl() CStr() CInt() CDate() 010
Option Explicit 005
Scope of Variable Public Level (Public) Module Level Global Variable (Dim, Private) 006 Global Variable Local Variable
Operator (1) Arithmetic Operator Operator Example Result Exponential ^ 6 ^ 4 1296 Multiplication * 6 * 4 24 Division / 6 / 4 1.5 Integral Division \ 6 \ 4 1 Remainder Mod 6 Mod 4 2 Addition + 6 + 4 10 Subtraction - 6 - 4 011
Operator (2) Comparison Operator Operator Example Result Smaller than < 6 < 4 False Smaller or Equal to <= 6 <= 4 Greater than > 6 > 4 True Greater or Equal to >= 6 >= 4 Equal to = 6 = 4 Not equal to <> 6 <> 4 Object comparison Is objA Is objB True/False String pattern comparison Like “UST“ Like "*me*" 011 When comparing objects, Is must be used. So objA = objB Runtime Error
Operator (3) String Operator Logic (or Boolean) Operator Operator Example Result String Connection & "ISOM" & "3230" "ISOM3230" + "ISOM" + "3230" "ISOM" + 3230 (Error) Operator Example Result Logical conjunction And 6 > 4 And 8 = 9 False Logical disjunction Or 6 > 4 Or 8 = 9 True Logical negation Not Not 6 > 4 011
Operator Precedence (1) Precedence Rules Operators are evaluated by following the precedence order table (next slide) Parentheses can override the order of precedence and the left associativity Operators with equal precedence are evaluated left to right in the order in which they appear in the expression
Operator Precedence (2) Type from Highest to Lowest Parentheses () Arithmetic and Concatenation ^ - (Negation) * / \ Mod + - (Add and subtract) & Comparison =, <>, <, <=,>,>=, Like, Is Logical Not And Or Xor Eqv Imp http://msdn.microsoft.com/en-us/library/gg278455.aspx a + = 1 ‘ Error in VBA
Sub and Function (1) 002
Sub and Function (2) When the return value of a function will be used immediately, brackets MUST be used. Sub test() Dim msg As Integer msg = MsgBox("Test 1", vbOKOnly) ' OK msg = msgbox "Test 2", vbOkOnly ' Error MsgBox "Test 3", vbOKOnly ' OK MsgBox("Test 4", vbOKOnly) ' Error End Sub 002
Passing Value to Method (1) 037 ArgumentName b ArgumentName a Remark := is to assign a value to a specific argument: ArgumentName := Value
Passing Value to Method (2) 038
Object Variable Must use Set Object variable name Class name Range object Range object .Value property Reset the object 007
If-Then 026
If-Then-Else 027
If-Then-Elseif 028
Select Case 029
For … Next Loop The counter value i must be declared outside For loop 030
Do While … Loop Cells() will return a Range Object Range Object 031 Color value Background color Remark: Cells( y , x ) Where x, and y are coordinates of a worksheet
Do Until … Loop Month(Date) A function returns an Integer specifying whole number between 1 and 12, inclusive, representing the month of the year. 032
Do … Loop While / Until Remark: Cells( y , x ) 033 Remark: Cells( y , x ) Where x can be a letter, instead of an integer
For Each … Next Update Remark: 034 Remark: - The Range Object covers data cells from B2 to D7 - Range( ”B2” , ”D7” ) same as Range( ”B2:D7” )
Exit Do / Exit For 035
Array Index starts from 0 Remark: 012 Remark: - Range( ”B2” ) same as Range( ”B2” ).Value
Option Base Option Base 1 / Option Base 0 The default array lower bound index will become 1 If you also specify the lower bound index during declaration: Dim Arr(2 To 5) As String Then Option Base will NOT change the lower bound index in this array 013
Array Initialization This also works Must use Variant MUST use Array keyword 014
Redim + Preserve 017
LBound + UBound 018 Calculating the array size: UBound(ArrayName) - LBound(ArrayName) + 1
Dynamic Array Remark: Range( ”A1” ).End(xlDown).Row 016 Remark: Range( ”A1” ).End(xlDown).Row Count the total number of valid data starting from A1 An empty cell contains invalid data
Object and Dot (.) Operator To access a property or method of an object, use the dot (.) operator between the object name (left operand) and the property / method name (right operand) Object Either Property (≈Variable) or Method Sub() Function() Workbooks.Count Dot Operator
Object and Dot (.) Operator Object.Property Object.Method Object.Sub() Object.Function()
A complicated example Range("B4").End(xlup).Select Object .Method Object .Select Cannot be determined: Maybe Sub() or Function() This Object can be generated from either Property (Object Variable) or Function (Returning Object). Function’s Returning Object: Function TestFunc() as Human Return New Human End Function Object variable: Objvar Dim Objvar as New Human (where Human is a class)
Model Answer: Range("B4").End(xlUp).Select
Range("B4").End(xlUp).Select 1 2 XlDirection Description xlDown Down xlToLeft To left xlToRight To right xlUp Up 3 4 Returning Object One parameter type is XIDirection
What is the data type of Return Value? Range.Select 1 2 3 4 What is the data type of Return Value? Mistake!!!
Range.Select
Workbook, Worksheet, and Range Objects Workbook Object a range of one cell Range Object a range of 5 cells Worksheet Object current sheet tab
Reference
Color Constant For reference Color constants: http://msdn.microsoft.com/en-us/library/gg278810.aspx Miscellaneous Constants http://msdn.microsoft.com/en-us/library/gg278800.aspx Constant Description vbBlack Black vbBlue Blue vbGreen Green vbCyan Cyan vbRed Red vbMagenta Magenta vbYellow Yellow vbWhite White Constant Description vbCrLf Carriage return–linefeed combination vbNewLine Platform-specific new line character; whichever is appropriate for current platform vbTab Tab character
Application.InputBox with specific parameters For reference Application.InputBox with specific parameters Application.InputBox(Prompt := Message, _ Title := Caption, _ Type := DataType) 024
Monitor a variable (1) For reference Step 1 Highlight the variable you want to monitor, right click and then select “Add Watch” 043
Monitor a variable (2) For reference Step 2 Select the Watch Type, and then press OK 043
Monitor a variable (3) For reference Step 3 The Watch Window will be shown. Click on the grey bar near your code to set a breakpoint. The program will pause once it reaches the breakpoint. 043
Monitor a variable (4) For reference Step 4 Press F5 to run the Sub. The program will pause at the breakpoint. The current value of the variable you watched will be shown on the Watch Window. You may also expand the content of the variable. 043