1 / 81

Memahami

Memahami. MS Excel. VBA. Dony Pranadiyanta, ST. VBA - Excel. VBA is Visual Basic for Applications The goal is to demonstrate how VBA can be used to leverage the power of Excel VBA syntax and usage the Excel VB programming environment the Excel object model an application. VBA - Excel.

sjoseph
Download Presentation

Memahami

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Memahami MS Excel VBA Dony Pranadiyanta, ST

  2. VBA - Excel • VBA is Visual Basic for Applications • The goal is to demonstrate how VBA can be used to leverage the power of Excel • VBA syntax and usage • the Excel VB programming environment • the Excel object model • an application

  3. VBA - Excel • What advantage is there in using VBA • extend Excel – new functions • makes it possible to use the Execl GUI environment • makes it possible to respond to events (mouse, …) • makes Windows programming API accessible • Excel can be used to control Automation servers (other software components that expose an API through COM) • by understanding how to use the Excel object model with VBA it is a small step to using Excel as an Automation server (controlled by other program)

  4. VBA - Excel • In order to run VBA code your security settings must be properly set • Tools | Macro | Security… • At least Medium security must be set – each macro will require user verification to run • Signed code can be run in all cases

  5. Objectives • Create a macro using the macro recorder • Work with the Project Explorer and Properties window of the VBA Editor • Edit a sub procedure • Run a sub procedure • Work with VBA objects, properties, and methods • Create an input box to retrieve information from the user New Perspectives on Microsoft Office Excel 2007

  6. Objectives • Create and run If-Then control structures • Work with comparison and logical operators • Create message boxes • Customize the Quick Access Toolbar • Customize Excel New Perspectives on Microsoft Office Excel 2007

  7. Developing an Excel Application • If the Excel Developer tab is not on the Ribbon, click the Office Button, click the Excel Options button, click Popular in the Excel Options dialog box (if necessary), click the Show Developer tab in the Ribbon check box to insert a check mark, and then click the OK button New Perspectives on Microsoft Office Excel 2007

  8. Working with the Visual Basic Editor • In the Code group on the Developer tab, click the Macros button • Clickthe macro name in the Macro name box, if necessary, and then click the Edit button New Perspectives on Microsoft Office Excel 2007

  9. Working with the Visual Basic Editor • A project is a collection of macros, worksheets, data-entry forms, and other items that make up the customized application you’re trying to create • Project Explorer is the window in the Visual Basic Editor that displays a hierarchical list of all currently open projects and their contents • The Project Explorer window is dockable • An object is any element within the Excel working environment such as a worksheet, cell, workbook, or even Excel itself New Perspectives on Microsoft Office Excel 2007

  10. Working with the Visual Basic Editor • A property is an attribute of an object that defines one of its characteristics, such as its name, size, color, or location on the screen • You can view a list of properties for any object in the Properties window • A module is a collection of VBA macros • The Code window displays the VBA macro code associated with any item in Project Explorer New Perspectives on Microsoft Office Excel 2007

  11. Working with the Visual Basic Editor New Perspectives on Microsoft Office Excel 2007

  12. Working with Sub Procedures • A sub procedure performs an action on your project or workbook, such as formatting a cell or displaying a chart • A function procedure returns a value • A property procedure is used to create custom properties for the objects in your project • Syntax refers to the set of rules that specify how you must enter certain commands so that VBA interprets them correctly • A comment is a statement that describes the behavior or purpose of a procedure, but does not perform any action New Perspectives on Microsoft Office Excel 2007

  13. Working with Sub Procedures New Perspectives on Microsoft Office Excel 2007

  14. Referring to Objects • VBA is an object-oriented programming language, in which tasks are performed by manipulating objects New Perspectives on Microsoft Office Excel 2007

  15. Referring to Objects • Objects are often grouped into collections, which are themselves objects, called collection objects New Perspectives on Microsoft Office Excel 2007

  16. Referring to Objects • VBA organizes objects and object collections in a hierarchy with the Excel application at the top and the individual cells of a workbook at the bottom New Perspectives on Microsoft Office Excel 2007

  17. Referring to Objects New Perspectives on Microsoft Office Excel 2007

  18. Applying Methods • A method is an action that can be performed on an object, such as closing a workbook or printing the contents of a worksheet New Perspectives on Microsoft Office Excel 2007

  19. Working with Variables and Values • A variable is a named element in a program that can be used to store and retrieve information • Every variable is identified by a unique variable name • Dim variable as type New Perspectives on Microsoft Office Excel 2007

  20. Retrieving Information from the User New Perspectives on Microsoft Office Excel 2007

  21. Working with Conditional Statements New Perspectives on Microsoft Office Excel 2007

  22. Working with Conditional Statements New Perspectives on Microsoft Office Excel 2007

  23. Working with Conditional Statements New Perspectives on Microsoft Office Excel 2007

  24. Working with Conditional Statements New Perspectives on Microsoft Office Excel 2007

  25. Creating a Message Box • MsgBox Prompt, Buttons, Title New Perspectives on Microsoft Office Excel 2007

  26. VBA – The Basics • Data types • Integer 2 byte integer • Long 4 byte integer • Single 4 byte floating point • Double 8 byte floating point • Currency 8 byte real • String upto 64K characters • Byte 1 byte • Boolean 2 byte true or false • Date 8 bytes • Object 4 bytes – an object reference • Variant 16 bytes + 1 byte / character

  27. Variables • Declare by Dim • Better to use Data Types:Dim amount AsDoubleDim year AsIntegerDim name AsString • Other data types: Boolean, Byte, Currency, Date • Default (no type) is Variant

  28. Variable(cont’d.) • % - integer & - long integer ! - single # - double@ currency $ - stringanIntegerValue% =3, aString$ = "hallo" • Can modify with scope (outside procedure)Private I AsIntegerPublic billsPaid AsCurrency • Make values permanentStatic yourName AsString • Multiple variablesPrivate test, amount, J AsInteger

  29. Constants • [Public|Private] Const constantName [As type] = expressionPublicConst PI = 3.1, NumPLANETS = 9Const PI2 = PI * 2Const RELEASE = #1/1/99/#

  30. VBA – The Basics • The variant data type is special – a variant can hold any type of data • A variable declared as variant (the default) can hold anything • The actual type of the data is kept in the data • It adds flexibility but at a cost – it requires more processing at compute time to determine what it is and how to handle it

  31. VBA – The Basics • Variables • must start with a letter • can contain _ and numbers • cannot exceed 255 characters in length • Within a procedure declare a variable using • If a variable is not declared it will be created when used, the type will be Variant • Use Option Explicit in the declarations section to require declaration of variables • VBA variables have scope restrictions • variables declared in a procedure are local to that procedure • variables declared in a module can be public or private Dim variable Dim variable As type

  32. VBA – The Basics • String variables • The first form is variable length • The second form is limited to 50 characters • the variable will be space filled if string is < 50 characters • the string will be truncated if the contents are > 50 characters • the Trim and RTrim functions are useful for working with fixed length strings • Boolean variables contain either True or False Dim variable As String Dim variable As String * 50

  33. VBA – The Basics • The Object type is used to store the address (a reference) of an object • this form can be used for any object • this is referred to as late-binding, the object types are checked at runtime (slower) • The declaration of a specific object is • this form will only store Excel Worksheet objects, an attempt to put anything else into it will result in an error • this is referred to as early-binding, the object types are checked at compile time (faster) Dim variable As Object Dim variable As Worksheet

  34. VBA – The Basics • Arrays are declared using • Arrays can be multidimensional • The lower bound starts at zero • can explicitly specify lower bound • can use Option Base command to reset to something other than 0 • The last form above is a dynamic array – it must be dimensioned using ReDim before it can be used • Use ReDim Preserve to retain any existing entries in array - only the upper bound of array can be changed Dim A (1 To 10) As Double Dim B (1 To 10, 1 To 10) As Double Dim C (4,4,4) As Integer Dim D () As Double Option Base 1

  35. VBA – The Basics • Constants are declared using • Constants have the same scope limitations as variables Const pi = 3.14159 Const pi As Double = 3.14159

  36. VBA – The Basics • User defined data types • can only be defined in the declarations section of a Module • can be Public or Private in scope • Declare variable with this type • Referencing fields Public Type SystemInfo CPU As Variant Memory As Long ColorBits As Integer Cost As Currency PurchaseDate As Date End Type Dim MySystem As SystemInfo MySystem.CPU = “Pentium” If MySystem.PurchaseDate > #1/1/2006# Then … End If

  37. VBA – The Basics • Watch out for • it is equivalent to Dim a, b, c As Integer Dim a As Variant Dim b As Variant Dim c As Integer

  38. VBA – The Basics • Objects • VBA can use pre-defined objects – such as intrinsic Excel objects • VBA can create user-defined objects – Class Modules • Declaring a variable to contain an object • the first form declares that the variable will contain a reference to an object of the named class • the second form declares the variable then creates an instance of the class • To instantiate a class Dim variable As class Dim variable As New class Set variable = New class

  39. VBA – The Basics • Objects • To declare a variable that will refer to an instance of the Excel Worksheet class • To put a reference into it • This fragment will print the name of the worksheet “Sheet1” Dim ws1 As Worksheet Set ws1 = Worksheets(“Sheet1”) Dim ws1 As Worksheet Set ws1 = Worksheets("sheet1") Debug.Print ws1.Name

  40. VBA – The Basics • Objects - Collections • There is a special form of objects known as Collections • They contain references to other objects and collections • It is the mechanism by which the object hierarchy is defined • By convention, collection names are usually plural • Workbooks – list of Workbook objects • Worksheets – list of Worksheet objects • Range – list of objects that represent cells, columns, rows • The following example iterates through Workbooks collection For Each ws In Worksheets Debug.Print ws.Name Next

  41. VBA – The Basics • Statements • VBA implements common programming statements • logical statements • looping statements • expressions

  42. VBA – The Basics • Logical statements • The If Then Else statement is the basic logic test If a>10 Then … End If If a>10 Then … Else … End If If a>10 Then … ElseIf a<0 Then … Else … End If

  43. VBA – The Basics • Logical statements • The Select statement can be used to replace a multi-way if statement Select Case expression Case expr1 … Case expr2 … Case Else … End Select

  44. VBA – The Basics • Loop statements • Various Do loop forms Do Until expr … Loop Do While expr … Loop Do … Loop Until expr Do … Loop While expr

  45. VBA – The Basics • Loop statements • A common For loop For i=1 To 10 Debug.print i Next i For i=1 To 10 Step 2 Debug.print i Next i

  46. VBA – The Basics • Loop statements • Another For loop • Commonly used to iterate through collections For Each element In group … Next element For Each ws In Worksheets Debug.Print ws.Name Next

  47. VBA – The Basics • Procedures • Procedures in VBA are either Macros or Functions • a macro does not return a value • a function will return a value • Property functions (Get and Let) are used in Class Modules to provide access to private properties Sub Name() … End Sub Function Name() As Double … End Sub

  48. VBA – The Basics • Dealing with runtime errors • The On Error statement will trap errors • The error name is a label in the code • In the error code a Resume statement will cause the statement that caused the error to be executed again • In the error code a Resume Next statement will restart execution on the statement after the one that caused the error … On Error GoTo label … On Error GoTo check … check: …

  49. VBA – Programming Environment • Excel (all Office components) have a VBA programming environment, VBIDE • It consists of • the Visual Basic Editor • an Object Browser • debugging support • These are accessed from the Excel menu • There is also a set of CHM files that document the components and object models of Office (for version 10) • the Excel file is named VBAXL10.CHM • XLMAIN10.CHM is the main help file for Excel and contains VBAXL10.CHM within it • each version of Office has its own set of files • http://www.ae.gatech.edu/classes/ae6382/documents/MS_Scripting/Office10/

  50. VBA – Programming Environment • To start the Visual Basic Editor from Excel select • Tools | Macro | Visual Basic Editor

More Related