Presentation is loading. Please wait.

Presentation is loading. Please wait.

ISOM3230 Business Applications Programming VBA Basic.

Similar presentations


Presentation on theme: "ISOM3230 Business Applications Programming VBA Basic."— Presentation transcript:

1 ISOM3230 Business Applications Programming VBA Basic

2 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 2

3 Outline 3 1.Developer Tab16.Operator 2.Enable Macro17.Operator Precedence 3.Trust Center18.Sub and Function 4.VBA Editor + Module19.Passing Value 5.Immediate Window20.If… End If 6.Comment21.Select Case 7.Debug.Print22.For… Next Loop 8.MsgBox23.Do While/Until… Loop 9.InputBox24.Do … Loop While/ Until 10.Data Type25.For Each… Next 11.Constant26.Exit Do/ Exit For 12.Declaring Variable27.Array 13.Converting Data Type28.Object Statement 14.Option Explicit29.Excel Environment 15.Scope of Variable28.Reference

4 Sub and Function 4 Debug.Print Developer Tab Enable Macro Trust Center VBA Editor + Module Immediate Window Passing Value MsgBox InputBox Constant Converting Data Type Declare & Assign Option Explicit Scope of Variable Object Variable Operator Operator Precedence If … End If Select Case For … Next Loop Do While/Until … Loop Do … Loop While/ Until For Each … Next Exit Do/ Exit For Option Base Color Constant Comment, _, and Main Data Type Environment + Basic In/output Variable Array Initialization Redim + Preserve Lbound + Ubound Dynamic Array Array Obj Condi. Stat. Iteration Array Application.InputBox Monitor a Variable Ref Operator Method Object Statement Excel Environment

5 End 5

6 6

7 7

8 Trust Center (1) 88

9 Trust Center (2) 9

10 VBA Editor + Module 10 Alt+F11

11 Immediate Window  Press Ctrl+G to open the Immediate Window 11

12 Use of Immediate Window (1) 12 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. 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.

13 Use of Immediate Window (2) 13 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 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

14 Comment, _, and Main Subroutine 14 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 - 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

15 Debug.Print 15

16 MsgBox 16 Remark: Messagebox.Show() is not available in VBA

17 InputBox 17 Remark: OK returns a String Cancel returns Nothing InputBox(Prompt, Title, Default )

18 Data Type 18 DataTypeDefault Value BooleanFalse Integer0 Double0 Date12:00:00 AM December 30, 1899 String“” VariantEmpty Remark: Variant is similar to the Object data type in VB

19 Constant 19 Declaring a constant _ is used here

20 Declaring Variable and Assigning Value 20 Must be separated

21 Converting Data Type 21 Remarks: All of the following are available in VBA CBool() CDbl() CStr() CInt() CDate() Build-in Constant

22 Option Explicit 22

23 Scope of Variable 23 Public Public Level (Public) Module Level DimPrivate (Dim, Private) Global Variable Local Variable

24 Operator (1) 24  Arithmetic Operator OperatorExampleResult Exponential^6 ^ Multiplication*6 * 424 Division/6 / 41.5 Integral Division\6 \ 41 RemainderMod6 Mod 42 Addition Subtraction

25 Operator (2)  Comparison Operator 25 OperatorExampleResult Smaller than<6 < 4False Smaller or Equal to<=6 <= 4False Greater than>6 > 4True Greater or Equal to>=6 >= 4True Equal to=6 = 4False Not equal to<>6 <> 4True Object comparisonIsobjA Is objBTrue/False String pattern comparisonLike“UST“ Like "*me*"True/False When comparing objects, Is must be used. So objA = objB  Runtime Error

26 Operator (3)  String Operator  Logic (or Boolean) Operator 26 OperatorExampleResult String Connection&"ISOM" & "3230""ISOM3230" String Connection+"ISOM" + "3230""ISOM3230" "ISOM" (Error) OperatorExampleResult Logical conjunctionAnd6 > 4 And 8 = 9False Logical disjunctionOr6 > 4 Or 8 = 9True Logical negationNotNot 6 > 4False

27 Operator Precedence (1) 27 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

28 Operator Precedence (2) Typefrom Highest to Lowest Parentheses () Arithmetic and Concatenation ^ - (Negation) * / \ Mod + - (Add and subtract) & Comparison =, <>,,>=, Like, Is Logical Not And Or Xor Eqv Imp a + = 1 ‘ Error in VBA 28

29 Sub and Function (1) 29

30 Sub and Function (2) 30 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 When the return value of a function will be used immediately, brackets MUST be used.

31 Passing Value to Method (1) 31 Remark := is to assign a value to a specific argument: ArgumentName := Value Remark := is to assign a value to a specific argument: ArgumentName := Value ArgumentName b ArgumentName a

32 Passing Value to Method (2) 32

33 Object Variable 33 Class nameObject variable name Must use Set Range object Reset the object Range object.Value property

34 If-Then 34

35 If-Then-Else 35

36 If-Then-Elseif 36

37 Select Case 37

38 For … Next Loop 38 The counter value i must be declared outside For loop

39 Do While … Loop 39 Background color Color value Range Object Remark: Cells( y, x ) Where x, and y are coordinates of a worksheet Cells() will return a Range Object

40 Do Until … Loop 40 Month(Date) A function returns an Integer specifying whole number between 1 and 12, inclusive, representing the month of the year. Month(Date) A function returns an Integer specifying whole number between 1 and 12, inclusive, representing the month of the year.

41 Do … Loop While / Until 41 Remark: Cells( y, x ) Where x can be a letter, instead of an integer

42 For Each … Next 42 Update Remark: - The Range Object covers data cells from B2 to D7 - Range( ”B2”, ”D7” ) same as Range( ”B2:D7” )

43 Exit Do / Exit For 43

44 Array 44 Remark: - Range( ”B2” ) same as Range( ”B2” ).Value Index starts from 0

45 Option Base 45 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 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 Option Base 1 / Option Base 0

46 Array Initialization 46 Must use Variant Array MUST use Array keyword This also works

47 Redim + Preserve 47

48 LBound + UBound 48 Calculating the array size: UBound(ArrayName) - LBound(ArrayName) + 1

49 Dynamic Array 49 Remark: Range( ”A1” ).End(xlDown).Row -Count the total number of valid data starting from A1 -An empty cell contains invalid data

50 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) 50 Workbooks.Count Dot Operator Object

51 Object and Dot (.) Operator  Object.Property  Object.Method 51 Object.Sub () Object.Function ()

52 A complicated example 52 Range("B4").End(xlup).Select Range("B4").End(xlup).Select Object.Select Object.Method Cannot be determined: Maybe Sub() or Function() Cannot be determined: Maybe Sub() or Function() This Object can be generated from either Property (Object Variable) or Function (Returning Object). Object variable: Objvar Dim Objvar as New Human (where Human is a class) Function’s Returning Object: Function TestFunc() as Human Return New Human End Function

53 Model Answer: Range("B4"). End(xlUp). Select 53

54 Range("B4").End(xlUp).Select 54 XlDirectionDescription xlDown Down xlToLeft To left xlToRight To right xlUp Up Returning Object One parameter type is XIDirection

55 55 Range.Select What is the data type of Return Value? Mistake!!!

56 Range.Select 56

57 Workbook, Worksheet, and Range Objects a range of one cell a range of 5 cells current sheet tab Workbook Object Worksheet Object Range Object

58 Reference 58

59 Color Constant Color constants: Miscellaneous Constants 59 For reference

60 Application.InputBox with specific parameters Application.InputBox(Prompt := Message, _ Title := Caption, _ Title := Caption, _ Type := DataType) Type := DataType) 60 For reference

61 Monitor a variable (1) 61 Step 1 Highlight the variable you want to monitor, right click and then select “Add Watch” Step 1 Highlight the variable you want to monitor, right click and then select “Add Watch” For reference

62 Monitor a variable (2) 62 Step 2 Select the Watch Type, and then press OK Step 2 Select the Watch Type, and then press OK For reference

63 Monitor a variable (3) 63 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. 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. For reference

64 Monitor a variable (4) 64 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. 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. For reference


Download ppt "ISOM3230 Business Applications Programming VBA Basic."

Similar presentations


Ads by Google