vb a developers guide

Upload: luisarmando5000

Post on 05-Apr-2018

236 views

Category:

Documents


1 download

TRANSCRIPT

  • 7/31/2019 Vb a Developers Guide

    1/284

    Microsoft Dynamics GP

    VBA Developers GuideRelease 9.0

  • 7/31/2019 Vb a Developers Guide

    2/284

    Copyright Copyright 2005 Microsoft Corporation. All rights reserved.

    Complying with all applicable copyright laws is the responsibility of the user. Without limiting therights under copyright, no part of this document may be reproduced, stored in or introduced into aretrieval system, or transmitted in any form or by any means (electronic, mechanical,photocopying, recording, or otherwise), or for any purpose, without the express written permissionof Microsoft Corporation. Notwithstanding the foregoing, the licensee of the software with whichthis document was provided may make a reasonable number of copies of this document solely forinternal use.

    Trademarks Microsoft, Excel, Microsoft Dynamics, Outlook, Visual Basic, and Windows are either registeredtrademarks or trademarks of Microsoft Corporation or its affiliates in the United States and/or othercountries. FairCom and c-tree Plus are trademarks of FairCom Corporation and are registered in theUnited States and other countries.

    The names of actual companies and products mentioned herein may be trademarks or registeredmarks - in the United States and/or other countries - of their respective owners.

    Unless otherwise noted, the example companies, organizations, products, domain names, e-mailaddresses, logos, people, places, and events depicted herein are fictitious. No association with any

    real company, organization, product, domain name, e-mail address, logo, person, place, or event isintended or should be inferred.

    Intellectual property Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectualproperty rights covering subject matter in this document. Except as expressly provided in anywritten license agreement from Microsoft, the furnishing of this document does not give you anylicense to these patents, trademarks, copyrights, or other intellectual property.

    Warranty disclaimer Microsoft Corporation disclaims any warranty regarding the sample code contained in this

    documentation, including the warranties of merchantability and fitness for a particular purpose.

    Limitation of liability The content of this document is furnished for informational use only, is subject to change withoutnotice, and should not be construed as a commitment by Microsoft Corporation. MicrosoftCorporation assumes no responsibility or liability for any errors or inaccuracies that may appear inthis manual. Neither Microsoft Corporation nor anyone else who has been involved in the creation,production or delivery of this documentation shall be liable for any indirect, incidental, special,exemplary or consequential damages, including but not limited to any loss of anticipated profit orbenefits, resulting from the use of this documentation or sample code.

    License agreement Use of this product is covered by a license agreement provided with the software product. If youhave any questions, please call the Microsoft Dyamics GPCustomer Assistance Department at 800-456-0025 (in the U.S. or Canada) or +1-701-281-6500.

    Publication date June 2006

  • 7/31/2019 Vb a Developers Guide

    3/284

    V B A D E V E L O P E R S G U I D E i

    Contents

    Introduction .................................................................................................................................2Whats in this manual ..................................................................................................................2

    Prerequisites ..................................................................................................................................2

    Product support ............................................................................................................................3

    Symbols and conventions ............................................................................................................3

    Whats next ....................................................................................................................................4

    Part 1: Using VBA ................................................................................................................6

    Chapter 1: VBA Overview .............................................................................................7The Visual Basic Editor ................................................................................................................7

    The VBA project ............................................................................................................................8

    Objects ..........................................................................................................................................10

    Programming model ..................................................................................................................12Using VBA with the Modifier .............................. .................................... ................................. 13

    Online help ..................................................................................................................................14

    Multiple third-party products ................................. ................................... ............................... 14

    Chapter 2: Programming Windows ...................................................................15Working with windows in a VBA project ............................... ................................. ............... 16

    Programming a window object ........................... .................................... ................................. 17

    Using window events ................................................................................................................18

    Window open events ................................ .................................... ................................... ........... 19

    Window close events ..................................................................................................................20

    Window activate events .............................................................................................................21

    Modal dialog events ................................. .................................... ................................... ........... 22

    Using window properties and methods. .................................................................................24

    Chapter 3: Programming Window Fields .....................................................31Working with window fields in your VBA project ................................................................32

    Programming a window field object ................................ ................................. ...................... 34

    Using window field events .................................. .................................. ................................... 35

    Got focus events ..........................................................................................................................36

    User changed events ..................................................................................................................38

  • 7/31/2019 Vb a Developers Guide

    4/284

    C O N T E N T S

    ii V B A D E V E L O P E R S G U I D E

    Changed event .................................. .................................... ................................... ................... 40

    Lost focus events ................................ .................................. ................................... ................... 41

    Using window field properties and methods ............................. ................................. .......... 43Working with field values ................................... ................................. .................................. ... 47

    Verifying field values .................................. .................................... ................................... ........ 51

    Window field type reference .............................. ................................. .................................... . 54

    Chapter 4: Programming Grids .............................................................................73Working with grids in your VBA project .............................. .................................... .............. 74

    Programming a grid object ................................. .................................... ................................. . 76Types of grids ...................................... .................................... ...................................... .............. 77

    Using grid events ................................. .................................... .................................... .............. 78

    Using grid properties and methods ............................... .................................... ..................... 82

    Chapter 5: Programming Reports .......................................................................83Working with reports in your VBA project ................................. ................................. .......... 83

    Using report events ................................. ................................... .................................... ............ 85

    Start/End events .............................. .................................... ................................... ................... 86

    Band events ................................ .................................... .................................... ......................... 87

    Using report properties and methods ............................... ................................. ..................... 91

    Working with report fields ............................... ................................... ................................... .. 92

    Exporting data to other applications .......................... ...................................... ....................... 95

    Chapter 6: Storing Additional Data ..................................................................97Understanding the DUOS ................................... ...................................... ................................ 97

    Structure of the DUOS .............................. ................................. .................................... ............ 98

    Working with DUOS data objects ............................... ................................. .......................... 100

    Retrieving a DUOS data object ................................ ................................. .............................. 101

    Deleting a DUOS data object ............................ ............................... .................................... ... 101

    Updating a DUOS data object ................................. ................................. .............................. 101

    DUOS properties and methods ................................. ................................. ............................ 102Using the DUOS ................................. .................................... ................................... ............... 103

    Chapter 7: Distributing a Project .....................................................................113Enabling VBA ............................................................................................................................113

    References to external components ........................................................................................113

    Distributing project files ...........................................................................................................115

  • 7/31/2019 Vb a Developers Guide

    5/284

    V B A D E V E L O P E R S G U I D E iii

    C O N T E N T S

    Package files ................................... .................................... ................................... .................... 116

    Package file import/export issues ............................... .................................. ........................ 119

    Part 2: VBA Object Library ..............................................................................122

    Chapter 8: Window Object .....................................................................................123Activate method. ...............................................................................................................124AfterActivate event ..........................................................................................................125AfterClose event .................................... ................................... .................................... .... 126AfterModalDialog event ..................................................................................................127AfterOpen event ...............................................................................................................130BeforeActivate event ........................................................................................................131BeforeClose event .............................................................................................................132BeforeModalDialog event ................................................................................................133BeforeOpen event .................................. ................................. .................................... ...... 136Caption property ..............................................................................................................137Changed property ............................... ...................................... .................................... .... 138Close method ..................................... .................................... ................................... ......... 139EventMode property ................................ .................................... ................................. .. 140Height property ................................. .................................... .................................... ...... 142Hide method ................................. ................................... .................................... ............. 143IsLoaded property .............................. ...................................... .................................... .... 144Left property ................................... ...................................... ................................... ......... 145Move method ...................................................................................................................146Name property ................................... .................................... .................................... ...... 147Open method .............................. .................................... .................................... ............... 148PullFocus method .............................................................................................................150Required property ............................................................................................................152

    Show method . ................................... ...................................... .................................... ...... 153Top property ................................... ...................................... ................................... ......... 154Visible property . ............................... .................................... ................................... ......... 155Width property ................................. .................................... ................................... ......... 157

    Chapter 9: Field Object .............................................................................................159AfterGotFocus event ........................................................................................................160AfterLostFocus event .......................................................................................................161AfterUserChanged event .................................................................................................162BeforeGotFocus event ......................................................................................................163BeforeLostFocus event .....................................................................................................164BeforeUserChanged event ...............................................................................................165Caption property ..............................................................................................................167Changed event ..................................................................................................................168Empty property .................................................................................................................170Enabled property ..............................................................................................................171Focus method ...................................... .................................... .................................... ...... 172FocusSeg method ................................ .................................. ................................... ......... 173

  • 7/31/2019 Vb a Developers Guide

    6/284

    C O N T E N T S

    iv V B A D E V E L O P E R S G U I D E

    Height property .............................. ................................... .................................... .......... 175Left property ..................................... .................................... ................................... ........ 176Locked property .............................. ................................... .................................. ............ 177Move method .................................... .................................... ................................... ........ 178Name property ................................... .................................... ................................... ...... 179Object property ............................. .................................... .................................... ............ 180Parent property. ................................. ................................. .................................... .......... 182Required property ................................. .................................... ................................. ...... 183TabStop property ............................... ................................. .................................... .......... 184Top property ................................... ...................................... ..................................... ...... 185Value property ..................................... ...................................... .................................... ... 186ValueSeg property ............................... .................................. ................................... ........ 189Visible property ................................ .................................... ................................... ........ 190Width property ................................. ...................................... ................................... ...... 191

    Chapter 10: Grid Object ............................................................................................193AfterLineChange event ................................. .................................... .............................. 194AfterLineGotFocus event ............................ ................................. .................................. . 195AfterLineLostFocus event ................................ ................................. .............................. 196BeforeLineChange event ............................... .................................... .............................. 197BeforeLineGotFocus event .............................. ................................. .............................. 198BeforeLineLostFocus event .............................. ................................. .............................. 199BeforeLinePopulate event .................................. ................................. ............................ 200Changed property ................................. .................................... ...................................... . 201EventMode property ................................ ................................. .................................... . 202Hide method ................................ .................................... ...................................... .......... 203Left property ..................................... .................................... ................................... ........ 204Move method .................................... .................................... ................................... ........ 205Name property ................................... .................................... ................................... ...... 207Show method .................................. ................................... .................................... .......... 208Top property ................................... ...................................... ..................................... ...... 209Visible property ................................. .................................... ................................... ........ 210

    Chapter 11: Report Object ......................................................................................211BeforeAF event ............................. .................................... .................................... ............ 212BeforeAH event ................................... .................................... ................................... ...... 213BeforeBody event ................................ .................................... ................................... ...... 214BeforePF event .............................. .................................. ................................... ............... 215BeforePH event .................................. .................................... ................................. .......... 216BeforeRF event ................................. ................................... .................................... .......... 217BeforeRH event. ................................. .................................... ................................... ........ 218Cancel method ..................................... ...................................... ...................................... . 219End event ............................... ................................... ...................................... ................... 220EventMode property ................................ ................................. .................................... . 221Legend property ................................ ...................................... ................................... ...... 222Name property ................................... .................................... ................................... ...... 223Start event. ............................... ................................... .................................... ................... 224

  • 7/31/2019 Vb a Developers Guide

    7/284

    V B A D E V E L O P E R S G U I D E v

    C O N T E N T S

    Chapter 12: VBAGlobal Object ...........................................................................225DUOSObjectCombineID method ...................................................................................226DUOSObjectExtractID method .......................................................................................228DUOSObjectsGet method ............................. .................................. ................................. 230

    Chapter 13: DUOSObjects Collection .........................................................233Exists property .............................. ................................... .................................... ............. 234Item property. .................................. ................................. .................................... ............. 235Name property .............................. ................................... .................................... ............. 236Remove method ..................................... ................................... .................................... .... 237SortByExisting property ...................................... ...................................... ...................... 238

    Chapter 14: DUOSObject Object ......................................................................241ID property .................................... ................................. .................................... ............... 242Properties property ...........................................................................................................243

    Chapter 15: DUOSProperties Collection ...................................................245Count property .............................. ................................... .................................... ............. 246Exists property .............................. ................................... .................................... ............. 247Item property. .................................. ................................. .................................... ............. 248Remove method ..................................... ................................... .................................... .... 250

    Chapter 16: DUOSProperty Object ................................................................251Name property .............................. ................................... .................................... ............. 252Value property ................................... ...................................... ...................................... .... 253

    Appendix ..................................................................................................................................256

    Appendix A: VBA Errors ...........................................................................................257Handling VBA errors .................................... ................................... ..................................... ... 257

    VBA error reference .................................... ...................................... .................................... .... 258

    Glossary .....................................................................................................................................265

    Index ...............................................................................................................................................269

  • 7/31/2019 Vb a Developers Guide

    8/284

    vi V B A D E V E L O P E R S G U I D E

  • 7/31/2019 Vb a Developers Guide

    9/284

    I NT R

    OD

    U CT I ON

  • 7/31/2019 Vb a Developers Guide

    10/284

    2 V B A D E V E L O P E R S G U I D E

    IntroductionMicrosoft Visual Basic for Applications, or VBA, is a standardprogramming language used by Microsoft Office products, as well as bymany other software providers who choose to embed VBA. Applicationssuch as Microsoft Dynamics GP host VBA as part of the Modifier. Thetools available in the VBA environment allow you to customize windows,fields and reports. In addition, you can attach VBA code to fields you createusing the Modifier.

    Whats in this manualThe VBA Developers Guide is designed to teach the basics of using VBAwith Microsoft Dynamics GP. The manual is divided into the followingparts:

    Part 1, Using VBA , provides information on how you can programwindows, window fields, grids and reports, as well as store additionalapplication data.

    Part 2, VBA Object Library , provides reference information aboutproperties, methods and events for objects in Microsoft Dynamics GP.

    Prerequisites

    Keep in mind that VBA is a powerful programming language, and a basicknowledge of VBA programming concepts is required. If you haventworked with VBA before, we strongly recommend you review one of themany books available that discuss programming with VBA.

    The remainder of the manual assumes that you are already familiar withVBAs programming concepts and features, as well as Microsoft DynamicsGP. It explains how to use your existing VBA knowledge to work with theVBA capabilities available with the accounting system.

  • 7/31/2019 Vb a Developers Guide

    11/284

    V B A D E V E L O P E R S G U I D E 3

    I N T R O D U C T I O N

    Product supportTechnical support for VBA can be accessed by the following methods:

    Telephone support Technical Support at (888) 477-7877 between 8:00a.m. and 5:00 p.m. Central Time, Monday through Friday. Internationalusers can contact Technical Support at (701) 281-0555.

    Internet VBA Technical Support is also available online throughCustomerSource or PartnerSource, and is accessible fromwww.microsoft.com/businesssolutions .

    Symbols and conventionsTo help you use the VBA documentation more effectively, weve used thefollowing symbols and conventions within the text to make specific types ofinformation stand out.

    Symbol Description

    The light bulb symbol indicates helpful tips,shortcuts and suggestions.

    Warnings indicate situations you should beespecially aware of.

    Margin notes summarize important information.

    Margin notes call attention to criticalinformation, and direct you to other areas of

    the documentation where a topic is explained.

    Convention Description

    Part 1, Using VBA Bold type indicates a part name.Chapter 1, VBAOverview

    Quotation marks indicate a chapter name.

    Setting window fields Italicized type indicates a section name.set 'l_Item' to 1. This font is used for VBA code examples.RUNTIME.EXE Words in uppercase indicate a file name.Visual Basic forApplications (VBA)

    Acronyms are spelled out the first time theyreused.

    TAB or ALT+M Small capital letters indicate a key or a keysequence.

  • 7/31/2019 Vb a Developers Guide

    12/284

    I N T R O D U C T I O N

    4 V B A D E V E L O P E R S G U I D E

    Whats next

    Before you can begin using VBA, be sure to complete the following tasks:

    1. Install Microsoft Dynamics GP.The runtime engine available with Microsoft Dynamics GP includes thecomponents necessary to support the VBA environment.

    2. Register the Modifier.To activate the VBA environment, you must register the Modifier. Theregistration keys to register the Modifier are supplied with theaccounting system. Once youve registered the Modifier, you can accessthe Visual Basic environment from the Tools menu.

    3. Review Chapter 1, VBA Overview.This chapter explains the basics of how the accounting systemintegrates with the Visual Basic environment. Once youve reviewedthe information in this chapter, you can use the remainder of themanual to learn specific ways you can use VBA with the accountingsystem.

  • 7/31/2019 Vb a Developers Guide

    13/284

    P

    ART 1 :

    U S I N

    G VBA

  • 7/31/2019 Vb a Developers Guide

    14/284

    6 V B A D E V E L O P E R S G U I D E

    Part 1: Using VBAUse the information in this portion of the documentation to understandhow to begin using VBA with Microsoft Dynamics GP. The following is alist of the topics discussed:

    Chapter 1, VBA Overview , explains the basics of the VBA environ-ment and how it integrates with Microsoft Dynamics GP. It alsoexplains the components of Microsoft Dynamics GP youll use whencreating projects in VBA.

    Chapter 2, Programming Windows , explains how to use VBA withthe window object.

    Chapter 3, Programming Window Fields , explains how to use VBAwith the window field objects.

    Chapter 4, Programming Grids , explains how to use VBA with the

    grid object (scrolling window).

    Chapter 5, Programming Reports , explains how to use VBA with thereport object.

    Chapter 6, Storing Additional Data , explains how to store user-defined data using the Dynamic User Object Store (DUOS).

    Chapter 7, Distributing a Project , explains how to package anddeliver a VBA project.

  • 7/31/2019 Vb a Developers Guide

    15/284

    V B A D E V E L O P E R S G U I D E 7

    Chapter 1: VBA Overview

    Before you start using VBA, its important that youre familiar with theVBA components specific to Microsoft Dynamics GP. The followingsections explain each of these in detail:

    The Visual Basic Editor The VBA project Objects Programming model Using VBA with the Modifier Online help Multiple third-party products

    The Visual Basic Editor

    You will use the Visual Basic Editor for building and maintaining a VBAproject. Once you register the Modifier, the Visual Basic Editor becomesaccessible from the Tools menu. The following illustration shows this menu:

    To open the Visual Basic Editor, point to Customize on the Tools menu, thenchoose Visual Basic Editor.

    Modifier and VBA menuoptions are available after you register the Modifier.

  • 7/31/2019 Vb a Developers Guide

    16/284

    P A R T 1 U S I N G V B A

    8 V B A D E V E L O P E R S G U I D E

    The following illustration shows how an existing project looks whenviewed in the Visual Basic Editor:

    The Visual Basic Editor is similar for each host application, so if youveused VBA with Microsoft Excel or Word, the Visual Basic Editor inMicrosoft Dynamics GP will be familiar.

    The VBA project

    The Visual Basic Editor stores customizations in a project file. The first timeyou open the Visual Basic Editor, the runtime engine automatically creates anew, empty project file that is named based on the current dictionary. Forexample the VBA project created for Microsoft Dynamics GP isDYNAMICS.VBA.

    If youre working with a third-party application, VBA creates a separate project to

    store customizations named NAME.VBA, where NAME is the name of the third- party products application dictionary.

    The Visual Basic Editor is the environment where

    youll define and maintaina VBA project.

  • 7/31/2019 Vb a Developers Guide

    17/284

    V B A D E V E L O P E R S G U I D E 9

    C H A P T E R 1 V B A O V E R V I E W

    You can view a project using the Visual Basic Project Explorer:

    Windows, reports and fields are not automatically part of the project. Whenyou begin working with VBA, youll selectively add to your project thewindow, field and report objects you want to work with. Once added toyour project, you can reference these objects in VBA. In addition, the VisualBasic Editor lets you add VBA user forms, user-defined procedures anduser-defined class modules to your VBA project.

    The VBA Editor lets you develop and maintain a single project at a time. Towork with several different projects, store each project file in a separatelocation. When you need to work on a project, copy it to the same locationof the runtime engine, then rename the file name.VBA, where name is thename of the dictionary the project is based on.

    After youve completed a VBA project file, youll distribute it to users. Thisfile contains your VBA code, the objects youve referenced in your VBAcode, and any VBA user forms you choose to use.

    Objects defined for your project appear in the

    Project Explorer.

  • 7/31/2019 Vb a Developers Guide

    18/284

    P A R T 1 U S I N G V B A

    10 V B A D E V E L O P E R S G U I D E

    Objects

    Applications expose their functionality to VBA through a set ofprogrammable objects. These objects include windows, reports, grids andDynamic User Object Store (DUOS) objects. The relationship each object hasto another object is expressed in a hierarchical object model, shown in thefollowing illustration:

    The organization of the model is important, since you must navigatethrough the object model within VBA code to access lower-level objects. Forexample, to access a window field, you must first indicate the fieldswindow object:

    'Set a field on a windowCustomerMaintenance.CustomerID.Value = "AARONFIT0001"

    The following sections explains each object in more detail.

    Window

    Window fields

    Report

    Report fields

    Grid

    Window fields

    DUOSObject

    DUOSproperty

    DUOSObjects

    DUOSProperties

    ObjectCollection Object

  • 7/31/2019 Vb a Developers Guide

    19/284

    V B A D E V E L O P E R S G U I D E 11

    C H A P T E R 1 V B A O V E R V I E W

    WindowsMost of the VBA programming youll complete for windows will involvethe following objects.

    Refer to Chapter 2, Programming Windows , and Chapter 3,Programming Window Fields , for more information about using VBA

    with windows.

    GridsGrids are VBAs definition of a scrolling window. When working withgrids, youll use the following objects:

    Refer to Chapter 4, Programming Grids , for more information aboutusing VBA with grids, and Chapter 3, Programming Window Fields , forinformation about programming window fields within a grid.

    ReportsWhen working with reports, youll use the following objects:

    Refer to Chapter 5, Programming Reports , for more information aboutusing VBA with reports.

    Object Description

    Window Represents an open window.

    Window field Represents a field in a window.

    Object Description

    Grid Represents a grid (scrolling window) in an open

    window.Window field Represents a field in a grid.

    Object Description

    Report Represents a report.

    Report field Represents a field in a report.

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    20/284

    P A R T 1 U S I N G V B A

    12 V B A D E V E L O P E R S G U I D E

    Dynamic User Object Store (DUOS)The Dynamic User Object Store (DUOS) allows you to store and displayuser-definable data.

    Refer to Chapter 6, Storing Additional Data , for more information aboutusing VBA with the DUOS.

    Programming model

    Each object in the object model has defined methods and properties you canuse in VBA code to manipulate the behavior of the object. Methods andproperties for objects are declared using standard VBA object.method and

    object.property syntax. Most objects also have specific events that specifywhen associated VBA code executes for the object.

    MethodsMethods are actions you can perform for a given object. Methods includeopening and closing a window or moving a field in a window. For example,the field object uses the Focus method to move the focus to a different fieldin the window:

    'Move the focus to the salesperson field

    SalespersonID.Focus

    PropertiesProperties are characteristics you can retrieve or set for a given object.Properties include the title of a window, or the value of a field. For example,you can use the Caption property to change the name of a window or field:

    'Change the prompt for a field

    CustomerMaintenance.CustomerID.Caption = "Patient ID"

    'Change the title of a window

    CustomerMaintenance.Caption = "Patient Maintenance"

    Object/Collection Description

    DUOSObjects collection Contains all user-definable data objects.

    DUOSObject object Represents a single data object.

    DUOSProperties collection Contains all properties for a data object.

    DUOSProperty object Represents a single property for a data object.

    C H A P T E R 1 V B A O V E R V I E W

  • 7/31/2019 Vb a Developers Guide

    21/284

    V B A D E V E L O P E R S G U I D E 13

    C H A P T E R 1 V B A O V E R V I E W

    EventsYoull write the majority of your VBA code within individual eventprocedures. Each event procedure executes VBA code at certain times for aspecific object, such as when the user changes the value of a field, clicks a button, prints a report, or opens a window. You can see these predefinedevent procedures in the VBA Code window.

    For example, BeforeOpen is an event for a window object. This eventexecutes the associated event procedure when the specified window opens.In the following example, the BeforeOpen event executes a procedurewhen the Receivables Transaction Entry window opens:

    Private Sub Window_BeforeOpen()

    SortBy.Value = 3 'Set the sort list to "by Date"

    DocumentType = 7 'Set the document type to "Returns"

    End If

    Using VBA with the ModifierRefer to the Modifier Users Guide for additional informationabout creating new fields for a window

    The primary reason to use VBA with the Modifier is to apply programminglogic to new fields you add to a window using the Modifier. By using VBAwith fields added using the Modifier, you can:

    Create push buttons that perform additional tasks, such as opening aVBA user form, launching another application, or performing calcula-tions. Refer to Chapter 3, Programming Window Fields , for moreinformation about using VBA with push button fields.

    Add new data entry fields that store additional data in the DynamicUser Object Store (DUOS). Refer to Chapter 6, Storing AdditionalData , for more information about using the DUOS.

    Object list.

    Event procedures specify

    when VBA code runs. The event procedures listed here are specific to

    window objects.

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    22/284

    P A R T 1 U S I N G V B A

    14 V B A D E V E L O P E R S G U I D E

    Online help

    After you install and register the Modifier, youll have access to online helpfor the Visual Basic Editor, the VBA programming language, and forobjects, methods and properties in Microsoft Dynamics GP. Use either ofthe following methods to display specific help topics:

    Open the help for Microsoft Dynamics GP. A link to the VBA help can be found there.

    Highlight a keyword in the Code window, such as an objects property

    or method and press F1. Context-sensitive help for that item willappear in the help window.

    Multiple third-party products

    By default, VBA can work with objects from the dictionary that the VBAproject is associated with. For example, the Microsoft Dynamics GP VBAproject can work with resources from the Microsoft Dynamics GPdictionary (Dynamics.dic). It is possible to have your VBA project referenceobjects in other dictionaries. To do this, you must create a reference in theVBA project to the other dictionary.

    To create a reference from a VBA project to another dictionary, select theVBA project in the VBA Explorer. Choose References from the Tools menuin the VBA environment. Mark the check box for the dictionary you want tomake references to.

    When creating references to other dictionaries, you cant have circular references.For example, if your Microsoft Dynamics GP VBA project references the Explorerdictionary, the VBA project for the Explorer dictionary cannot have a reference backto the Microsoft Dynamics GP project.

  • 7/31/2019 Vb a Developers Guide

    23/284

    V B A D E V E L O P E R S G U I D E 15

    Chapter 2: Programming WindowsProgramming windows using VBA involves adding a window to yourproject, specifying the window events youll use to execute VBA code, andusing window methods and properties to customize window display.

    Information about programming windows is divided into the followingsections:

    Working with windows in a VBA project Programming a window object Using window events Window open events Window close events Window activate events Modal dialog events Using window properties and methods

    Youll also likely want to customize a window using the windows fieldsand scrolling windows (grids). Refer to Chapter 3, Programming WindowFields , and Chapter 4, Programming Grids , for detailed informationabout working with window fields and grids.

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    24/284

    16 V B A D E V E L O P E R S G U I D E

    Working with windows in a VBA project

    In order to use VBA with a Microsoft Dynamics GP window, youll firstneed to add the window to your project. Adding a window creates acorresponding window object in your project, which you can reference inVBA.

    Adding a window objectTo add a window object to your project, switch to Microsoft Dynamics GPand display the window you want to add. On the Tools menu, point toCustomize, then choose Add Current Window to Visual Basic. This will addthe currently-active (topmost) window to your project. The followingillustration shows this menu:

    Switch to the Visual Basic Editor and display the Project Explorer. It shouldlook similar to the following:

    This item adds the active window to your VBA

    project.

    The Project Explorer displays the window objects youve

    added to the project. Objects for third-party applications

    appear in a separate project.

    C H A P T E R 2 P R O G R A M M I N G W I N D O W S

  • 7/31/2019 Vb a Developers Guide

    25/284

    V B A D E V E L O P E R S G U I D E 17

    You can continue to switch between the Visual Basic Editor and the mainapplication to add windows as needed throughout your projectsdevelopment. When viewed in the accounting system, each window youve

    added to your project will appear with a period (.) at the end of thewindows title. This provides technical support and VBA developers with avisual cue that the window is part of the VBA project.

    Removing a window objectTo remove a window object from your project, switch to MicrosoftDynamics GP and display the window you want to remove. On the Toolsmenu, point to Customize, then choose Remove Current Window From

    Visual Basic. VBA will remove the window and any window fieldsassociated with the window.

    Be sure you remove from your project all references to a window after youveremoved it.

    Programming a window object

    There are two primary ways you can write VBA code for a window object:using a window event procedure, or referencing the window in proceduresthroughout your project.

    Using a window event procedureA window event procedure executes VBA code when a user opens, closesor activates a window in Microsoft Dynamics GP. This is useful for settingdefault window field values when the window opens, or closing other

    windows when the window closes. In the following example, an eventprocedure sets default field values when the Invoice Entry window opens:

    Private Sub Window_AfterOpen()

    'Set the sort list to "by Date"

    SortBy = 3

    'Set the document type list to "Returns"

    DocumentType = 2

    End Sub

    The following section, Using window events, explains each type of windowevent you can use to execute VBA code. Windows also contain windowfields that you can reference and manipulate through VBA. Refer toChapter 3, Programming Window Fields , for more information aboutusing window fields.

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    26/284

    18 V B A D E V E L O P E R S G U I D E

    Referencing the window objectAfter you create a window object in your project, any VBA code you writein your VBA project has full access to the window object, its properties andits methods. In the following example, a push button on a VBA form opensa window using the windows Open method:

    Private Sub OpenCustomerMaintenance_Click()

    CustomerMaintenance.Open

    End Sub

    The section titled Using window properties and methods explains the methods

    and properties available to procedures in your VBA project.

    Using window events

    Refer to Chapter 8,Window Object, for adetailed explanationand example of each

    window event described here.

    A window event executes a specific VBA procedure (an event procedure)when a user opens, closes or activates a window, or when a message dialogappears for the window. To view the window events available, select aMicrosoft Dynamics GP window object in your project, then display the

    Visual Basic Code window. Select Window in the Object list; window eventswill appear in the Procedure list.

    A window event executes an event procedure either beforeor after MicrosoftDynamics GP application code runs for the same event. Therefore, windowevents use names like BeforeClose to indicate that the event runs as thewindow closes but beforeMicrosoft Dynamics GP application code runs forthe window. When you choose an event, VBA automatically adds the eventprocedure syntax to the Code window.

    Select Window in the Object list.

    When you choose anevent, the Code window

    adds event procedure syntax automatically.

    Window events appear inthe Procedures list.

    C H A P T E R 2 P R O G R A M M I N G W I N D O W S

  • 7/31/2019 Vb a Developers Guide

    27/284

    V B A D E V E L O P E R S G U I D E 19

    If you use VBA with a window youve modified using the Modifier, youmust set the EventMode property to emModified if you want events tooccur for the modified window. To change the EventMode property for the

    window object, use the Visual Basic Properties window.

    If you delete a modified window from your forms dictionary (or delete the formsdictionary altogether), all VBA references to new fields you add to the modifiedwindow will be invalid. If you re-create the modified window, then re-add the new fields using the Modifier, youll need to re-add those same fields to your VBA project and re-create any VBA customizations that reference the new fields.

    Window open eventsVBA window open events occur when the user opens the window, eitherbeforeor after the Microsoft Dynamics GP code for the window open eventruns. Microsoft Dynamics GP uses the window open event to set defaultfield values, such as a default document date or a sorting order.

    BeforeOpen eventThe BeforeOpen event occurs beforethe Microsoft Dynamics GP code runsfor the window open event. Its useful when you want to set default fieldvalues in the window, while still allowing any Microsoft Dynamics GPapplication code to override your defaults. In the following example, theevent procedure sets the Checkbook ID field when the Invoice Batch Entrywindow opens. If this window displays an existing record when opened(such as when opened from a zoom field), Microsoft Dynamics GPapplication code overrides this value with the value stored with the record:

    Private Sub Window_BeforeOpen(OpenVisible As Boolean)

    'Set the checkbook ID

    CheckbookID = "PETTY CASH"

    End Sub

    This event also includes the OpenVisible parameter. When set to False, thisspecifies that the window should open invisibly.

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    28/284

    20 V B A D E V E L O P E R S G U I D E

    AfterOpen eventThe AfterOpen event occurs after the Microsoft Dynamics GP code runs forthe window open event. Its useful for overriding any default values thatwere set for window fields. In the following example, the event proceduremarks both check box controls when the Sales Territory Maintenancewindow opens. Since Microsoft Dynamics GP application code sets defaultsfor these fields when the window opens, using the AfterOpen eventoverrides the defaults:

    Private Sub Window_AfterOpen()

    'Set both check boxes when the window opens

    MaintainHistory = 1MaintainHistory1 = 1

    End Sub

    Window close events

    VBA window close events occur when the user closes the window, eitherbeforeor after the Microsoft Dynamics GP code for the window close event

    runs. Microsoft Dynamics GP uses the window close event to display amodal dialog asking the user whether to save changes to the record.

    BeforeClose eventThe BeforeClose event occurs before Microsoft Dynamics GP applicationcode runs for the window close event. The primary use for this event is tocancel the window close if the contents in the window dont meet certaincriteria. The following event procedure for the Invoice Entry window

    checks whether the user entered a comment ID for the transaction, anddisplays a message dialog. If the user clicks Yes, the procedure cancels theclose using the AbortClose parameter, and the user can enter a comment ID:

    Private Sub Window_BeforeClose(AbortClose As Boolean)

    Dim Response As Integer

    If CommentID.Empty = True Then

    'Display a message box

    Response = MsgBox("Do you want to enter a Comment?", vbYesNo)

    If Response = vbYes Then

    'They want to enter a comment

    AbortClose = True

    CommentID.Focus

    End If

    End If

    End Sub

    C H A P T E R 2 P R O G R A M M I N G W I N D O W S

  • 7/31/2019 Vb a Developers Guide

    29/284

    V B A D E V E L O P E R S G U I D E 21

    AfterClose eventThe AfterClose event occurs after the Microsoft Dynamics GP applicationcode runs for the window close event. The AfterClose event is a general-purpose event you can use to perform any clean-up tasks, such as closingother windows. For example, the following event procedure runs when theCustomer Maintenance window closes. It closes the Customers AndProspects lookup window if its open (its IsLoaded property is True):

    Private Sub Window_AfterClose()

    If CustomersAndProspects.IsLoaded = True Then

    CustomersAndProspects.Close

    End IfEnd Sub

    Window activate events

    VBA window activate events occur when the user activates a window,either by opening it or by making it the frontmost window.

    The BeforeActivate event occurs before any Microsoft Dynamics GPapplication code runs for the window activate event. The AfterActivateevent occurs after any Microsoft Dynamics GP application code runs for thewindow activate event.

    Microsoft Dynamics GP rarely executes application code during a window activateevent. Therefore, whether you choose theBeforeActivate or AfterActivate eventmay be of little consequence.

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    30/284

    22 V B A D E V E L O P E R S G U I D E

    Modal dialog events

    A modal dialog is a specific type of window that requires the user to

    perform some action in order to dismiss the dialog. The most commonmodal dialog is an ask dialog, where message text and one or more buttonsappear in the window. A modal dialog appears in the following illustration:

    You apply a modal dialog event to a window in the same manner as otherwindow events. However, instead of occurring when the window opens,

    closes or activates, the modal dialog event occurs for the window whenevera modal dialog opens.

    BeforeModalDialog eventThe VBA BeforeModalDialog event occurs when Microsoft Dynamics GPopens a modal dialog, but beforeits displayed. Since the dialog is open, butnot visible, this event allows you to dismiss the dialog by programmaticallyanswering it for the user. In the following example, if a user enters a non-

    existent shipping method in the Customer Maintenance window, MicrosoftDynamics GP displays an ask dialog asking whether the user wants to addthe shipping method. Normally the user must dismiss the dialog manually, by clicking Add or Cancel. Instead, the event procedure automaticallyanswers this dialog and removes a step in the data entry process:

    Private Sub Window_BeforeModalDialog(ByVal DlgType As Boolean, _

    PromptString As String, Control1String As String, Control2String _

    As String, Control3String As String, Answer As Long)If PromptString = "Do you want add this Shipping Method?" Then

    'Click the first button, the Add button

    Answer = dcButton1

    End If

    End Sub

    PromptString

    Control1String

    Control2String Control3String

    C H A P T E R 2 P R O G R A M M I N G W I N D O W S

  • 7/31/2019 Vb a Developers Guide

    31/284

    V B A D E V E L O P E R S G U I D E 23

    The PromptString parameter is the message text, which you can use to filterwhich modal dialog you want to respond to. The Answer parameter usesthe constants dcButton1 , dcButton2 and dcButton3 . When indicated, these

    click the first, second or third button in the dialog.

    The BeforeModalDialog event is also useful for altering the contents of thedialog before its displayed, including the modal dialogs message text and button text. The following event procedure changes the message and buttontext:

    Private Sub Window_BeforeModalDialog(ByVal DlgType As Boolean, _

    PromptString As String, Control1String As String, Control2String _

    As String, Control3String As String, Answer As Long)

    If PromptString = "Do you want to add this shipping method?" Then

    'Change the message text

    PromptString = "Create this shipping method?"

    'Change "Add" button to "Create"

    Control1String = "Create"

    End If

    End Sub

    AfterModalDialog eventThe VBA AfterModalDialog event occurs when Microsoft Dynamics GPopens a modal dialog, but after the user dismisses it. This event allows youto ascertain how the user responded to the dialog and perform anyadditional tasks based on that response.

    Refer to Chapter 6,Storing Additional Data, for more information about using the Dynamic User Object Store (DUOS).

    The primary use for the AfterModalDialog event is to keep data in theaccounting system synchronized with data youve stored using theDynamic User Object Store (DUOS). For instance, if youve created a DUOSobject that stores Internet address information for a customer, youll likelywant to save it when the user saves the corresponding customer record.

    In the following example, the user attempts to close a window withoutsaving a customer record. In this case, Microsoft Dynamics GP will displaya modal dialog asking if the user wants to save the record. If the user clicksthe modal dialogs Save button, the event procedure saves thecorresponding DUOS object:

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    32/284

    24 V B A D E V E L O P E R S G U I D E

    Private Sub Window_AfterModalDialog(ByVal DlgType As Long, _

    PromptString As String, Control1String As String, _

    Control2String As String, Control3String As String, Answer As Long)

    Dim Customers As DUOSObjectsDim Customer As DUOSObject

    Dim CustomerProperty As DUOSProperty

    If PromptString = "Do you want to save changes to this " + _

    "customer?" Then

    'The user is trying to save the record using the save dialog.

    If Answer = dcButton1 Then 'The user clicked Save.

    Set Customers = DUOSObjectsGet("Customers")

    Set Customer = Customers(CustomerID)

    Customer.Properties("URL Address") = URLAddress

    Customer.Properties("Contact E-Mail Address") = _

    ContactEMailAddress

    End If

    End If

    End Sub

    Using window properties and methodsRefer to Chapter 8,Window Object, for detailed explanations and examples of the window properties and methods described here.

    The following table explains the available window methods and properties.The remainder of this section explains some of the more common methodsand properties youll use when working with windows, as well asadditional ways you can use windows.

    Property/Method Description

    Activate method Activates the window.Caption property Specifies the windows title.

    Close method Closes the window.

    EventMode property Specifies whether window events occur for theoriginal or modified version of the window.

    Height property Specifies the height of the windows client area (inpixels). The client area is the window less thewindows title bar.

    Hide method Hides an open window.IsLoaded property Specifies whether the window is open (not necessarily

    displayed).

    Left property Specifies the horizontal position (in pixels) of thewindow.

    Move method Moves a window to a specified set of coordinates (inpixels).

    C H A P T E R 2 P R O G R A M M I N G W I N D O W S

  • 7/31/2019 Vb a Developers Guide

    33/284

    V B A D E V E L O P E R S G U I D E 25

    Opening and closing windowsYou can open a Microsoft Dynamics GP window directly or indirectlythrough VBA. To open and close it directly, use the window objectsOpen method and Close method . The following event procedure opens theCustomer Maintenance window after the user logs in:

    Private Sub Window_AfterClose()

    'The user logged in. Open the Customer Maintenance window.

    CustomerMaintenance.Open

    End Sub

    The recommended method is to open a window indirectly, using VBA toprovide the navigation that displays the window, such as programmaticallyclicking a lookup button that displays a lookup window:

    Private Sub ShippingMethod_AfterGotFocus()

    If ShippingMethod.Empty = True Then

    'No shipping method specified. Click the lookup button

    LookupButtons = 1

    End If

    End Sub

    Microsoft Dynamics GP application code attached to navigational controls(such as the lookup button) prepares the window to display data correctly.Clicking these controls using VBA ensures that this processing occurs.

    Name property Specifies the internal name VBA uses for the window.

    Open method Opens a window.

    PullFocus method Removes the focus from the window.

    Show method Shows a window thats hidden using the Hide method.

    Top property Specifies the vertical position of the window (inpixels).

    Visible property Specifies whether the window is visible.WidthpropertySpecifies the width of the window (in pixels).

    Required property Specifies whether the user entered data in all fieldswhose Required property is True.

    Property/Method Description

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    34/284

    26 V B A D E V E L O P E R S G U I D E

    Working with formsIn Microsoft Dynamics GP, forms are a logical grouping of windows thatfunction together to perform a specific task. For instance, the Customer

    Maintenance, Customer Account Maintenance and Customer MaintenanceOptions windows are all part of the same form.

    When you open a window, Microsoft Dynamics GP opens all windows inthe windows form invisibly, then displays the first window in the form (theparent window). The child windows in the form remain invisible, butloaded (their IsLoaded property is True).

    If you open a forms child window through VBA, Microsoft Dynamics GPdisplays the forms parent window as well as the child window. Any otherchild windows remain loaded and invisible.

    When you display a record in the parent window, Microsoft Dynamics GPupdates data in the invisible child windows so each contains data specificto the current record. Since these child windows are loaded, you canreference data in these fields using VBA.

    For instance, when you open the Customer Maintenance window anddisplay a customer record, you can reference fields in the CustomerMaintenance Options window for that customer. In the following example,the event procedure stops the user from saving a customer record in theCustomer Maintenance window if the user hasnt entered a currency ID inthe Customer Maintenance Options window:

    Private Sub Save_BeforeUserChanged(KeepFocus As Boolean, _

    CancelLogic As Boolean)

    If CustomerMaintenanceOptions.CurrencyID.Empty = True Then

    'Cancel the save

    CancelLogic = True

    'Prompt the user to enter a currency ID

    MsgBox "You must enter a currency ID for this customer."

    CustomerMaintenanceOptions.Visible = True

    CustomerMaintenanceOptions.CurrencyID.Focus

    End If

    End Sub

    Use the Modifiers Form Definition window to find out which windows arepart of a form.

    C H A P T E R 2 P R O G R A M M I N G W I N D O W S

  • 7/31/2019 Vb a Developers Guide

    35/284

    V B A D E V E L O P E R S G U I D E 27

    Activating a windowThe VBA Activate method activates a visible, open window, making it thefrontmost window, or expands it if its minimized. The Activate method

    also causes the windows activate event to occur. In the following example,the event procedure activates the Invoice Entry window after closing theInvoice Batch Entry window:

    Private Sub Window_AfterClose()

    If InvoiceEntry.Visible = True Then

    InvoiceEntry.Activate

    End If

    End Sub

    Hiding windowsThe VBA Hide method hides a window youve opened, making it invisible.The Visible property , when set to False, also makes a window invisible.While invisible, the window is open (its IsLoaded property is True) anddata in the window is accessible.

    Making a window invisible is useful if you need to reference data contained

    in the window without necessarily displaying the window to the user. Forexample, when the user enters a transaction amount in the ReceivablesTransaction Entry window, the following event procedure compares theamount with the maximum batch total in an invisible Receivables BatchEntry window:

    Private Sub SalesAmount_BeforeUserChanged(KeepFocus As Boolean, _

    CancelLogic As Boolean)

    If BatchID.Empty = False Then

    'The user selected a batch

    'Click the expansion button to open the Batch Entry window

    ExpansionButtons = 1

    'Make the window invisible

    ReceivablesBatchEntry.Visible = False

    'Compare the batch total to the trx amount entered

    If CCur(SalesAmount) >CCur(ReceivablesBatchEntry _

    .BatchTotal) Then

    MsgBox "Amount exceeds batch limit. Select another batch."

    'Clear the batch ID field and move the focus there

    BatchID.Empty = True

    BatchID.Focus

    End If

    'Close the window

    ReceivablesBatchEntry.Close

    End If

    End Sub

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    36/284

    28 V B A D E V E L O P E R S G U I D E

    The Show method displays an invisible window. Setting the windowsVisible property to True also displays an open window. You can open awindow invisibly by setting the OpenVisible parameter of the windows

    BeforeOpen event to False.

    Moving and resizing a windowYou can resize or reposition a window using the Height property ,Left property , Top property and Width property . Resizing andrepositioning a window is useful for organizing windows more efficientlywithin the visible workspace. In the following example, the eventprocedure runs when the Customer Maintenance window opens. In

    Microsoft Dynamics GP, the default behavior is to display this window ontop of the Sales Cards palette. In this case, the event procedure checks if theSales Cards palette is open, then positions the Customer Maintenancewindow to the right of the palette:

    Private Sub Window_BeforeOpen(OpenVisible As Boolean)

    If SalesCards.Visible = True Then

    'The Sales Cards palette is open

    CustomerMaintenance.Left = SalesCards.Width + SalesCards.Left

    CustomerMaintenance.Top = SalesCards.Top

    End If

    End Sub

    Changing a window titleThe Caption property allows you to set the windows caption (title). Thefollowing example checks the current company displayed in the Toolbar

    window, then changes the title of the CustomerMaintenance window whenthe window opens:

    Private Sub Window_BeforeOpen(OpenVisible As Boolean)

    If Toolbar.CompanyID = "ASPECT REALTY, INC" then

    'Change the title of the window

    CustomerMaintenance.Caption = "Client Maintenance"

    CustomerMaintenance.CustomerID.Caption = "Client ID"

    End If

    End Sub

    C H A P T E R 2 P R O G R A M M I N G W I N D O W S

  • 7/31/2019 Vb a Developers Guide

    37/284

    V B A D E V E L O P E R S G U I D E 29

    Using modified or original windowsYou can choose whether window events occur for the modified or originalversion of a window using the EventMode property . If you modify a

    window using the Modifier, you can change the windows EventModeproperty to emModifiedOnly. This allows VBA events to occur for themodified window only.

    If you make no modifications to the window using the Modifier, you can setthe EventMode property to emOriginalOnly. This allows VBA events tooccur for the original window only.

    Renaming a windowThe Name property allows you to change VBAs internal reference to awindow object. Note that this is not the same as the Caption property ,which allows you to change the windows title. If you change the windowsName property using the Visual Basic Properties window, the name willchange in your project. You should then recompile your project to replaceany references to that window with the new name. Youll find it necessaryto rename a window if its name conflicts with other object names in your

    project, such as reserved words in VBA.

  • 7/31/2019 Vb a Developers Guide

    38/284

    30 V B A D E V E L O P E R S G U I D E

  • 7/31/2019 Vb a Developers Guide

    39/284

    V B A D E V E L O P E R S G U I D E 31

    Chapter 3: Programming Window FieldsProgramming window fields using VBA involves adding a window or agrid to your project, then adding selected field objects from that window orgrid. Programming window fields also involves determining whichwindow field events youll use to execute VBA code, and using windowfield methods and properties to customize field display characteristics, or tochange business logic in a window. Information about programmingwindow fields is divided into the following sections:

    Working with window fields in your VBA project

    Programming a window field object Using window field events Got focus events User changed events Changed event Lost focus events Using window field properties and methods Working with field values

    Verifying field values Window field type reference

    P A R T 1 U S I N G V B A

  • 7/31/2019 Vb a Developers Guide

    40/284

    32 V B A D E V E L O P E R S G U I D E

    Working with window fields in your VBA project

    To use window fields with VBA, youll first need to add a window and its

    window fields to your project.

    Adding window fields to your projectTo add window fields, switch to Microsoft Dynamics GP and display thewindow. On the Tools menu, point to Customize, then choose Add WindowTo Visual Basic. This adds the active (topmost) window to your project.With the window displayed, point to Customize on the Tools menu andchoose Add Field To Visual Basic. This will activate field selection mode,

    and a selection pointer will appear. The following illustration shows theselection pointer:

    Using the mouse, click on each data entry field, push button or list fieldyoull use in your project. Be sure to click on the field itself, and not thefields prompt. When youve finished adding fields, point to Customize onthe Tools menu, and choose Add Fields to Visual Basic to deactivate fieldselection mode.

    Field selection mode also deactivates when you switch to the Visual Basic Editor.

    Window fields youve added to a project wont appear in the Visual BasicProject Explorer like a window, report or grid object. Instead, they willappear in the Visual Basic Code window for a window object.

    Position the selectionpointer on the field (not

    the prompt) and click.

    C H A P T E R 3 P R O G R A M M I N G W I N D O W F I E L D S

  • 7/31/2019 Vb a Developers Guide

    41/284

    V B A D E V E L O P E R S G U I D E 33

    The following illustration shows window field objects for the ReceivablesCustomer Maintenance window object:

    At this point, you can write VBA code for the window field object using awindow field event, or you can reference the window field from other VBAprocedures in your project.

    Removing window fields from your projectYou cannot remove individual field objects from your project, only windowobjects. When you remove a window object from your project, VBA alsoremoves the all window field objects associated with the window.

    To remove a window object from your project, switch to MicrosoftDynamics GP and display the window you want to remove. On the Toolsmenu, point to Customize, then choose Remove Current Window FromVisual Basic. VBA will remove the window and any window fieldsassociated with it.

    The windows fields appear in the Code

    window for the window object.

    P A R T 1 U S I N G V B A

    P i i d fi ld bj

  • 7/31/2019 Vb a Developers Guide

    42/284

    34 V B A D E V E L O P E R S G U I D E

    Programming a window field object

    There are two primary ways you can write VBA code for a window field

    object: using a window field event procedure, and referencing the windowfield in procedures throughout your project.

    Using window field event proceduresA window field event lets you execute VBA code when the user moves to,changes or moves out of a specific field. This is useful when you want toperform actions based on entries made in the field. The following section,Using window field events, explains window field events in more detail.

    Referencing the window fieldTo reference a windows fields, the field must be an object in your project,and the fields window must be open (the windows IsLoaded property isTrue).

    If the field youre referencing is not in the current window, you mustreference the field using a qualified field name. A qualified name explicitly

    specifies the location of the field youre referencing. In the followingexample, an event procedure for a VBA user form opens the Invoice BatchEntry window, then clicks a lookup button using the lookup button fieldsqualified name:

    Private Sub CommandButton1_Click()

    'Open the batch entry window

    InvoiceBatchEntry.Open

    'Click the lookup button to display the lookup

    InvoiceBatchEntry.LookupButton1 = 1

    UserForm1.Hide

    End Sub

    C H A P T E R 3 P R O G R A M M I N G W I N D O W F I E L D S

    U i i d fi ld t

  • 7/31/2019 Vb a Developers Guide

    43/284

    V B A D E V E L O P E R S G U I D E 35

    Using window field eventsRefer to Chapter 9,Field Object, for more examples of window field events.

    Window field events execute VBA procedures when a user moves to,changes, or moves out of a window field, or a field youve added using theModifier. To view field events, choose a field object in the Code windowsObject list; all the window field events will appear in the Procedure list.

    When you choose an event, VBA automatically adds the event proceduresyntax to the Code window. You can then write the event procedure usingthat event syntax.

    There are four basic kinds of field events youll work with in VBA: got focus,user changed, changed and lost focus. Each event occurs relative to when theuser moves the focus into a field (a got focusevent), when the value of a fieldchanges (a user changed or changed event) or when the user moves the focusout of a field (a lost focusevent).

    These events are useful when you want to respond to data the user enters ina field by performing other operations in the window. For example, thefollowing AfterUserChanged event procedure runs when the user changesinformation in the State field:

    Private Sub State_AfterUserChanged()

    If State = "NJ" Then

    'Default the salesperson and territory

    SalespersonID = "MARILYN H."

    TerritoryID = "TERRITORY 4"

    End IfEnd Sub

    Select the window field object in the Object list.

    Event syntax appears automatically when you

    choose an event.

    Window field events appear in the

    Procedure list.

    P A R T 1 U S I N G V B A

    Field events also respond to actions performed by the user such as clicking

  • 7/31/2019 Vb a Developers Guide

    44/284

    36 V B A D E V E L O P E R S G U I D E

    Field events also respond to actions performed by the user, such as clickinga button. In the following example, a new button (OpenMSWord) added toa window using the Modifier uses the AfterUserChanged event to open

    Microsoft Word:Private Sub OpenMSWord_AfterUserChanged()

    Dim App As Word.Application

    Set App = CreateObject("Word.Application")

    App.Visible = True

    End Sub

    Each window field event you define occurs either before or after theMicrosoft Dynamics GP code for the field event runs. Therefore, fieldevents have names like BeforeUserChanged to indicate that the eventruns when the user changed the contents, but beforethe Microsoft DynamicsGP application code runs.

    Got focus events

    VBA got focus events occur when the user initially enters a field, using theTAB key or the mouse. You can use two VBA events, BeforeGotFocus andAfterGotFocus , to execute VBA event procedures beforeand after the codefor the got focus event runs.

    For information about setting fields from afield event procedure,refer to Setting field values on page 50.

    The BeforeGotFocus , AfterGotFocus and BeforeUserChanged events are theonly three window field events where VBA allows you to set the value of thecurrent field (the field whose events are running).

    The following illustration shows the progression of got focus events:

    User moves the focus to the Name field: 1. VBA BeforeGotFocus event occurs for the Name field.2. Microsoft Dynamics GP got focus event occurs.3. VBA AfterGotFocus event occurs.

    C H A P T E R 3 P R O G R A M M I N G W I N D O W F I E L D S

    If Microsoft Dynamics GP runs application code during the got focus event

  • 7/31/2019 Vb a Developers Guide

    45/284

    V B A D E V E L O P E R S G U I D E 37

    If Microsoft Dynamics GP runs application code during the got focus event,it typically checks the value of the field thats gaining focus, and performscalculations or sets other field values based on that value. However,

    Microsoft Dynamics GP uses this event infrequently to do such operations.BeforeGotFocus eventThe BeforeGotFocus event occurs beforethe Microsoft Dynamics GP codefor the got focus event. Use this event to set or evaluate the contents of thefield gaining focus, and cancel any further got focus events from running(the Microsoft Dynamics GP got focus event and the VBA AfterGotFocusevent). When set to True, the CancelLogicparameter will cancel the fields

    other got focus events. In this example, theBeforeGotFocus

    eventprocedure cancels the AfterGotFocus event for the Batch ID field (shown inthe description of the AfterGotFocus event below):

    Private Sub BatchID_BeforeGotFocus(CancelLogic As Boolean)

    If DocumentType = 7 Then

    'The document type is a return. Dont use a batch

    BatchID.Empty = True

    'Cancel the AfterGotFocus event, which opens the lookup

    CancelLogic = True

    MsgBox "Post returns individually, not in a batch."

    DocumentDate.Focus

    End If

    End Sub

    AfterGotFocusThe AfterGotFocus event occurs after the Microsoft Dynamics GP code runsfor the got focus event. Use this event to set or evaluate the contents of afield gaining focus. In the following example, the AfterGotFocus event forthe Batch ID field checks whether the field is empty when the user moves toit. If it is, the event procedure opens the batch lookup window:

    Private Sub BatchID_AfterGotFocus()

    If BatchID.Empty = True Then

    'The field is empty. Click the lookup button

    LookupButton3 = 1

    End If

    End Sub

    P A R T 1 U S I N G V B A

    User changed events

  • 7/31/2019 Vb a Developers Guide

    46/284

    38 V B A D E V E L O P E R S G U I D E

    User changed eventsVBA user changed events occur when the user changes the contents of afield, then moves the focus out of the field, using the TAB key or the mouse.In fields that toggle, such as push buttons and visual switches, the userchanged event occurs when the user clicks the field. In list fields, the userchanged event occurs when the user selects an item in the list.

    You can use two VBA events, BeforeUserChanged and AfterUserChanged ,to execute VBA events either beforeor after the Microsoft Dynamics GP codefor the user changed event runs.

    For information about setting fields from afield event procedure,refer to Setting field values on page 50.

    The BeforeGotFocus , AfterGotFocus and BeforeUserChanged events are theonly three window field events where VBA allows you to set the value of thecurrent field (the field whose events are running).

    The following illustration shows the progression of user changed events inan editable field:

    Its common for Microsoft Dynamics GP to use the user changed event toverify the contents of a field when the field changes; however, this isntdone for all fields.

    In fields that toggle, such as push buttons and visual switches, the userchanged event occurs when the user clicks the field. Microsoft DynamicsGP always executes application code during the user changed event forthese fields.

    User enters information in the Name field and presses the TAB key: 1. VBA BeforeUserChanged event occurs for the Name field.2. Microsoft Dynamics GP user changed event occurs for the Name field.3. VBA AfterUserChanged event occurs for the Name field.

    User clicks the Save button: 1. VBA BeforeUserChanged event occurs for the button.2. Microsoft Dynamics GP user changed event occurs for the button.3. VBA AfterUserChanged event occurs for the button.

  • 7/31/2019 Vb a Developers Guide

    47/284

    P A R T 1 U S I N G V B A

    AfterUserChanged

  • 7/31/2019 Vb a Developers Guide

    48/284

    40 V B A D E V E L O P E R S G U I D E

    gThe AfterUserChanged event occurs after the Microsoft Dynamics GP codefor the user changed event runs. Use this event to evaluate information the

    user entered in a field. The following example uses the AfterUserChangedevent to check the value of the Customer ID field in the Invoice Entrywindow, then disable the Trade Discount field:

    Private Sub CustomerID_AfterUserChanged()

    If CustomerID = "ADVANCED0002" Then

    'Don't offer a trade discount

    TradeDiscount.Enable = False

    End If

    End Sub

    Changed event

    The VBA Changed field event always occurs for a field when its contentschange. This includes:

    When the user changes the field directly WhenMicrosoft Dynamics GP application code updates the window

    field When a fields value changes using an external tool, such as VBA

    The most common situation to use the Changed event is when you want toexecute VBA code for window fields that Microsoft Dynamics GP updates.This occurs most often when the accounting system retrieves a record froma table, then displays the records contents in window fields. TheAfterUserChanged and BeforeUserChanged events wont occur for thesefields, since the application, not the user, changes the contents of the field.

    Exercise caution when using the Changed event. In many cases, MicrosoftDynamics GP may cause the Changed event to occur numerous times for the same field even though the value of the field may not visibly change. This will execute theassociated VBA event procedure each time the event occurs.

    For example, as the user browses through records in the ReceivablesTransaction Entry window, Microsoft Dynamics GP sets window fieldvalues for each record. The following Changed event procedure runs forthe Document Date field. Each time the user moves to a new record, itchecks the value of the document date, and displays a message if thedocument is older than 30 days:

    C H A P T E R 3 P R O G R A M M I N G W I N D O W F I E L D S

    Private Sub DocumentDate_Changed()

  • 7/31/2019 Vb a Developers Guide

    49/284

    V B A D E V E L O P E R S G U I D E 41

    Dim DaysOld As Integer

    'Check the document date using the VBA Date function

    If CDate(DocumentDate) < Date - 30 Then

    'The document is at least 30 days old

    DaysOld = Date - CDate(DocumentDate)

    MsgBox "This document is " + Str(DaysOld) + " days old." + _

    "Please post."

    End If

    End Sub

    Lost focus events

    VBA lost focus events occur when the user exits a field, using the TAB key orthe mouse, regardless of whether the fields contents changed. You can usetwo VBA events, BeforeLostFocus and AfterLostFocus , to execute VBAevent procedures beforeand after the Microsoft Dynamics GP code for thelost focus event runs.

    The following illustration shows the progression of lost focus events:

    Microsoft Dynamics GP rarely uses the lost focus event. When it is used, ittypically locks control fields (fields that control the display of a record).

    BeforeLostFocusThe BeforeLostFocus event occurs beforethe Microsoft Dynamics GP codefor the lost focus event. You can use the BeforeLostFocus event to cancelany subsequent lost focus events for the field. When set to True, theCancelLogic parameter cancels the Microsoft Dynamics GP lost focus andVBA AfterLostFocus events.

    User exits the Name field: 1. VBA BeforeLostFocus event occurs for the Name field.2. Microsoft Dynamics GP lost focus event occurs.3. VBA AfterLostFocus event occurs.

    P A R T 1 U S I N G V B A

    The following BeforeLostFocus event procedure runs for the DocumentN b fi ld i th R i bl T ti E t i d Thi i

  • 7/31/2019 Vb a Developers Guide

    50/284

    42 V B A D E V E L O P E R S G U I D E

    Number field in the Receivables Transaction Entry window. This is acontrol field, and normally the lost focus event locks this field. In this case,the procedure cancels all other lost focus events, and the DocumentNumber field remains unlocked and editable:

    Private Sub Number_BeforeLostFocus(KeepFocus As Boolean, _

    CancelLogic As Boolean)

    CancelLogic = True

    Description.Focus = True

    End Sub

    When set to True, the KeepFocusparameter allows you keep the focus in thecurrent field.

    AfterLostFocusThe AfterLostFocus event occurs after the Microsoft Dynamics GP coderuns for the lost focus event. You can use the AfterLostFocus event toevaluate the value of the field losing focus, and perform any additionaloperations in the window. The following AfterLostFocus event procedurechecks whether the Payment Terms field is empty. If it is, the proceduredisplays a VBA dialog that asks the if the user wants to enter a paymentterm. If the user clicks Yes, the procedure opens the Payment Terms Lookupwindow:

    Private Sub PaymentTerms_AfterLostFocus()

    Dim Response As Integer

    If PaymentTerms.Empty = True Then

    'Set a default payment termResponse = MsgBox("Do you want to enter a payment term?", _

    vbYesNo)

    If Response = vbYes Then

    LookupButtons = 1

    End If

    End If

    End Sub

    C H A P T E R 3 P R O G R A M M I N G W I N D O W F I E L D S

    Using window field properties and methods

  • 7/31/2019 Vb a Developers Guide

    51/284

    V B A D E V E L O P E R S G U I D E 43

    Refer to Chapter 9,Field Object, for detailed explanations and examples of eachwindow field property and method.

    The following table explains the available methods and properties for

    window fields. The remainder of this section explains some of the morecommon methods and properties youll use when working with windowfields.

    Disabling and locking fieldsThe Enabled property and Locked property allow you to make a fieldread-only and inaccessible to the user. To disable a field, set the Enabledproperty to False. A disabled field will appear dimmed, and any relatedcontrols (such as lookup or expansion buttons) will be inaccessible. To locka field, set its Locked property to True. A locked field will appear with agray background, and its related controls will s