VB &VBA IN A NUTSHELL The Language VB &VBA IN A NUTSHELL The Language Paul Lomax Beijing • Cambridge • Farnham • Kưln • Paris • Sebastopol • Taipei • Tokyo VB & VBA in a Nutshell: The Language by Paul Lomax Copyright © 1998 O’Reilly & Associates, Inc All rights reserved Printed in the United States of America Published by O’Reilly & Associates, Inc., 101 Morris Street, Sebastopol, CA 95472 Editor: Ron Petrusha Production Editor: Mary Anne Weeks Mayo Printing History: October 1998: First Edition Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly & Associates, Inc The association of the image of a Newfoundland dog and the topic of VB & VBA is a trademark of O’Reilly & Associates, Inc IntelliSense, Microsoft, MS-DOS, PowerPoint, Visual Basic, Visual C++, Win32, Windows, and Windows NT are registered trademarks, and ActiveX, Outlook, and Visual Studio are trademarks of Microsoft Corporation Visio is a registered trademark of Visio Corporation Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly & Associates, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein This book is printed on acid-free paper with 85% recycled content, 15% postconsumer waste O’Reilly & Associates is committed to using paper with the highest recycled content available consistent with high quality ISBN: 1-56592-358-8 [4/99] Table of Contents Preface vii Part I: The Basics Chapter 1—Introduction What Is VBA? A Brief History of VBA What Can You Do with VBA? Object Models: The Power of Programming with VBA Chapter 2—Program Structure 11 Getting a VB Program to Run 12 The Structure of a VB Program 19 Ending Your VB Program 23 Chapter 3—VBA Variables and Data Types 26 Visual Basic Data Types Type Conversion The Variant Declaring Variables and Constants Array Variables User-Defined Types Variable Scope and Lifetime Object Variables and Binding Passing Parameters Intrinsic Constants v VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved 26 31 33 37 39 45 46 47 50 53 Chapter 4—Class Modules 54 Properties Enumerated Constants Class Module Events Implementing Custom Class Methods Creating ActiveX Components Using ActiveX Components in a Project 55 62 63 68 70 75 Chapter 5—Automation 77 Creating Object Model References Reading the Object Model Working with the Object Model Collection Objects Trapping an Automation Server’s Events Automation Examples Automation Performance Tips 77 79 81 83 84 85 89 Chapter 6—Error Handling 91 Building a Robust Application 92 Error Handling in Procedures 95 Error Handling in ActiveX Servers 101 Reporting Errors 104 Part II: Reference Chapter 7—The Language Reference 111 Part III: Appendixes Appendix A—Language Elements by Category 583 Appendix B—Language Constants 598 Appendix C—Operators 606 Appendix D—What’s New in VB6? 613 Index 617 vi VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved Preface Before we go any further, let’s just clarify one fundamental point Visual Basic for Applications (VBA) is the language used to program in Visual Basic (VB) VB itself is a development environment; the language element of that environment is VBA Similarly, VBA is the language used to program all the applications in the Microsoft Office suite except Outlook, as well as a whole host of third-party applications The VBA language (with a very few minor exceptions) is the same whether you’re programming within VB or creating an application in a hosted VBA environment such as Word or Excel Unless specifically noted, the language elements described in this book can be used exactly the same in both the retail version of VB and the hosted VBA environment; consequently throughout the book I often interchange the terms VB and VBA While it’s important to emphasize that this book is a reference to a language component that’s shared by VB and by applications that host VBA, it’s also important to emphasize that it is not any of the following: • A reference guide to VB controls and to their properties, events, and methods These belong to the Visual Basic environment and aren’t part of VBA at all They are, however, documented in the forthcoming Visual Basic Controls in a Nutshell, written by Evan S Dictor and published by O’Reilly & Associates • A reference guide to UserForms and their controls, all of which are defined by one or another version of the Microsoft Forms Library Very much like VB controls, these belong to the hosted VBA IDE and aren’t part of the language proper • A reference guide to the individual object models of the Office suite By accessing its host application’s object model VBA can automate the application Nevertheless, both conceptually and practically, VBA code and object model code are distinct components Some of the object models, however, are documented in the Programming the…Object Model series, published by vii VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved Why Another VB Book? O’Reilly & Associates These include Programming the Access/DAO Object Models, by Helen Feddema, and Programming the Word Object Model, by Julianne Sharer and Arthur Einhorn Why Another VB Book? VBA is the single most important language for any developer to learn and master The large numbers of people beginning VB and VBA programming, as well as the enormous number of current VB programmers who wish to deepen their knowledge and programming skills, is attested to by the wealth of published material about VB Yet, there still is a desperate need for a detailed, professional reference of the VBA language There are literally hundreds of books lining the shelves about how to program using Visual Basic or how to use VBA to automate Office applications—seemingly each one promising to teach you more quickly than the rest But if you’re new to VB, you won’t learn it overnight, or even in a few short weeks; VBA is a large and detailed language, with hundreds of different functions, statements, and language elements Furthermore, because the Basic language has been developed over many years (portions even having their origin in Basic and QBasic), and each new version has to accommodate code written using the previous version, you will find that most tasks can be achieved in a number of different ways There may be the really old function, the not-so-old function, and the brand-new function, all of which achieve a similar result—but which is the old one and which is the new one? Which one should you use? Is the new one really that much better than the old one? This depth of information is where the experience of using a language for many years, through all versions of VB and VBA, comes into play, and it is this experience that I hope to impart through this book What’s Wrong with the Online Help? In a word, nothing The online help accompanying VB and VBA is an indispensable resource and one that most developers depend on What this book does is take up where the help section leaves off, to give you the full picture Contained within these pages are the experiences of professional VB developers who have used the VBA language in both VB and as a hosted language in Office applications all day, every day, over many years, to create complex mission-critical applications It’s these experiences that you can benefit from Whether you have come to VB recently or have been using VB for years, there are always new tricks to learn And it’s always important to find out about the gotchas that’ll getcha! For the most part, the documentation with VB and VBA isn’t bad; it just doesn’t have the depth of information you need when you need it Most of us can get by day to day without even opening the help section But when you need to open the help section, it’s probably because you’ve either hit an unexpected problem or need to know what the consequences of coding a particular procedure in a particular way will be However, the help sections tend only to show you how a function should be included in your code This is understandable; after all, the help sections for any language by their very nature must be created before that language goes into general use, but it is only general, everyday use in real-life situ- viii Preface VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved Preface ations that highlights how the language can best be used and what its problems and pitfalls are Therefore, online help confines itself to the main facts: what the syntax is and, in a general way, how you should implement the particular function or statement A quick note here about the help section in VB6: Microsoft has decided to move the help section into MSDN and to convert it from WinHelp to HTML Help During the prerelease stages, the new UI has come in for a lot of criticism for being slow, memory hungry, and unintuitive (to say the least!) I hope therefore that you’ll read up on the new VB6 language features and then keep this book close to hand Who Should Read This Book? This book is aimed at professional software developers The VBA language is the most widely used rapid application development, or RAD, language in the world, and in addition to the millions of developers now using VBA, many more developers are coming into the VB arena from other languages, such as C++, not so much to replace those skills, but to augment their personal toolkit and to enhance their career opportunities This book is a reference work and not a tutorial, so, for example, I won’t explain the concept of a For Next loop; as a professional developer, you already know this, so you don’t want someone like me insulting your intelligence But I will detail how a For Next loop works in VB, how it works in practice, what the alternatives to it are, how it can be used to the best advantage, and what pitfalls it has and how to get round them I also hope this book will be the main reference for experienced VB developers who are upgrading to VB6 I have spent several months working with VB6 in order to become familiar with and fully document the important new language elements and object models within it Here again, though, if you’re a VB developer upgrading to VB6, you don’t want to be led by the hand like a newbie through the additional functions and object models; you know that your familiarity with the VBA language means that you can pick up the new features of VB6 quickly You just need to know how this stuff works in the real world, and you’ll be off and running An Emphasis on Professional VB Development Because the VBA language is increasingly important for creating mission-critical applications, I have concentrated where appropriate on using language elements in a multiuser environment, detailing points of particular note for when you are programming components destined for an n-tier application model and for use within environments such as DCOM and Microsoft Transaction Server In the same vein, I have also noted any differences found using language elements in NT and Windows 95 Another pet peeve of mine is the readability and maintainability of VB code Most corporate VB applications are now created by development teams rather than an individual programmer It’s therefore important to ensure that any member of the team can get up to speed quickly when maintaining your code, and of course that Preface VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved ix How This Book Should Be Used you can understand what it was you where trying to when you wrote the code several months earlier! With this in mind, I have also noted—where necessary— tips to improve the readability and self-documenting character of your VB code How This Book Should Be Used Well, to get here you’ve obviously passed the first hurdle, which is turning the pages; now all you need to is read the words! If You’re a Developer New to VB If you are new to the VBA language, then this book assumes that VBA is your second or subsequent language The first half of the book leads you through the important areas of programming VB and VBA style, which, while very different from most other languages, are straightforward and easily mastered I suggest therefore that you read these chapters in order while referring to Chapter when necessary If You’re a VB or VBA Developer As an experienced developer, you can dip into the book to get the lowdown on a language element that interests you Appendix A details all the functions, statements, and object models by category to help you find the relevant section in Chapter more easily If You’re a VB or VBA Developer New to VB6 Appendix D is a good place to start; it lists the new and amended language features and language-related object models in VB6 Work your way through this list, referring to the relevant sections in Chapter While VB6 isn’t the major leap forward that VB4 and VB5 were, you’ll find some powerful additions that enhance both the speed at which you can develop an application and the quality of your applications Note that because this book is specifically about the language, new VB6 nonlanguage features such as dynamic control addition aren’t included How This Book Is Structured This book is divided into three parts The first part of the book, The Basics, is an introduction to the main features and concepts of Visual Basic programming Even seasoned VB professionals should find items of interest here If you’re new to VB, this part of the book is essential reading It’s divided into the following chapters: Chapter 1, Introduction In this chapter, you’ll find information on what the VBA language is and how it fits in to the family of VB products There’s also a short discussion of the history of VBA Chapter 2, Program Structure This chapter details how you create the basic program structures in VB and VBA; how you implement procedures, functions, and properties; and how you start and stop VB and VBA programs x Preface VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved E early binding, 48, 76, 78, 89 (see also data binding) elements, array, 40 concatenating, 396–397 filtering out of arrays, 308–310 parsing strings into, 524–525 resetting values of, 252 email within VB (example), 86–88 Empty subtype (Variant), 34 encapsulation, 54 end of file, 249–252 End statements, 25, 245–246 ending VB programs, 23–25 Enum statement, 63, 246–248 enumerated constants, 62–63, 246–248 intrinsic (built-in), 598–605 Environ, Environ$ functions, 248–249 environment variables, values of, 248–249 EOF function, 249–252 equal to (=) operator, 607 Eqv operator, 609 Erase statement, 252 Err object, 100, 253–264, 585 Error subtype (Variant), 34 errors, 91–107 in ActiveX servers, 101–104 checklist for handling, 92–95 CVErr function, 183–185 Err object, 100, 253–264, 585 error messages to users, 104 Error statement, 265–266 Error, Error$ functions, 265 handling in ActiveX components, 73 Help to prevent, 104 IsError function, 391–392 logging, 106 On Error statement, 440–442 in procedures, 95–100 for undefined variables, 445 event-driven programs, 11 events, 19 Automation Server, trapping, 84, 576–578 calling functions/methods upon, 20–21 of class modules, 63–68 custom, 66–68, 266–268 622 DoEvents function, 241–242 errors (see errors) event handlers, defined, 64 Event statement, 67, 266–268 explicitly creating, 23 firing (see firing events) keyboard key presses assigning VB macros to, 15, 17 simulating with SendKeys, 508–511 user actions, launching VB programs at, 14, 16 Excel (Microsoft), running VBA modules, 15–17 VB output to (example), 88 executables (VB), running, 17 execution flow, 23, 594 EXEs (see out-of-process ActiveX EXEs) existence check Dictionary keys, 226–227 drives, 291–292 files, 292–293 folders, 293–294 IsEmpty function, 390–391 IsMissing function, 393 IsNull function, 394 Exists method (Dictionary), 226–227 Exists property, 74 Exit statement, 268–269 Exit Sub statement, 99 Exp function, 269 exponentiation (^) operator, 607 extension, filename, 297–298 externally createable objects, 81 F FileExists method (FileSystemObject), 292–293 filename extensions, 297–298 files accessing data from, 350–352, 376–379, 405–406, 552–553 Lock/Unlock statements with, 415–417, 567–568 CopyFile method (FileSystemObject), 283–284 copying (see copying files) CreateTextFile method (FileSystemObject), 287–289 Index VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved CreateTextFile method (Folder), 315–316 Delete method (Folder), 316–317 DeleteFile method (FileSystemObject), 289–290 deleting, 272–273, 289–290, 397–398 Dir, Dir$ functions, 236–238 EOF function, 249–252 File object, 270–275, 588, 616 File System Folders collection, 616 File System object, 616 File System object model, 275–276 FileAttr function, 276–278 FileAttribute type, 600 FileCopy statement, 278–279 FileDateTime function, 279–280 FileExists method (FileSystemObject), 292–293 FileLen function, 280–281 Files collection object, 281–282, 588, 616 FileSystemObject object, 282–308, 586 FreeFile function, 337–338 GetAttr function, 355 GetExtensionName method (FileSystemObject), 297–298 GetFile method (FileSystemObject), 298–299 GetFileName method (FileSystemObject), 299–300 GetTempName method (FileSystemObject), 303 handling (functions/statements list), 589 help files, 258–259 Move method (Folder), 317–318 MoveFile method (FileSystemObject), 303–304 opening/closing, 162–163, 274–275, 442–444, 491, 551 OpenTextFile method (FileSystemObject), 306–308 read/write position, 415, 504–505 SetAttr function, 516–517 vbFileAttribute type, 600 width of, 574 writing to, 478–479, 554, 554–555, 578–579 (see also folders) Filter function, 308–310 finances CCur function, 32 Currency data type, 27 FormatCurrency function, 334–335 functions for (list), 589 firing events custom events, 67, 482–483 Initialize event, 64 Terminate event, 65 first week of the year, 202 Fix function, 310–311 fixed arrays, 40 fixed-length strings, 29 floating point numbers converting to, 32, 151–152, 161–162, 180–181 data types for, 28 flow control, 23, 594 focus, setting to application, 123–125 folders Add method (Folders), 319–320 Copy method (Folder), 314–315 CopyFolder method (FileSystemObject), 285–286 CreateFolder method (FileSystemObject), 286–287 CreateTextFile method (Folder), 316–317 creating new, 427 DeleteFolder method (FileSystemObject), 290–291 deleting, 290–291, 316–317, 496–498 Dir, Dir$ functions, 236–238 File System Folders collection, 616 Folder object, 311–318, 587 FolderExists method (FileSystemObject), 293–294 Folders collection object, 318–319, 587 Folders object, 616 GetAttr function, 355 GetFolder method (FileSystemObject), 300–301 Index VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved 623 folders (continued) GetParentFolderName method (FileSystemObject), 301 GetSpecialFolder method (FileSystemObject), 302–303 GetTempName method (FileSystemObject), 303 handling (functions/statements list), 589 Move method (Folder), 317–318 MoveFolder method (FileSystemObject), 304–306 SetAttr function, 516–517 SpecialFolderConst type, 603 (see also files) For Each Next loops, 322–325 in ActiveX components, 72 implementing in custom collection objects, 73 iterating through collections, 84 For Next statement, 320–322 Format, Format$ functions, 325–334 FormatCurrency, FormatNumber, FormatPercent functions, 334–335 FormatDateTime function, 336–337 formatting (see data formatting) forms binding controls (see data binding) defining properties in, 56 Form Load event, 17–18 loading into memory, 406–408 removing from memory, 566–567 running at startup, 17–18 unloading from memory, 24 FreeFile function, 337–338 Friend keyword, 47 friend scope class methods, 69 properties, 59 variables, 47 functions, 22, 112 Call statement, 141–142 calling, 20–21, 23 custom class methods, 68–69 defining (Function statement), 338–349 mass assignation functions, 62 624 new for VB6 (list), 615 returning arrays, 614 strongly typed, variants and, 37 sub procedures vs., 68, 94–95 (see also procedures) FV function, 349–350 G Get property procedure, 23, 59, 464–468 Get statement, 350–352 GetAbsolutePathName method (FileSystemObject), 294–295 GetAllSettings function, 352–354 GetAttr function, 355 GetAutoServerSettings function, 356–358 GetBaseName method (FileSystemObject), 295 GetDrive method (FileSystemObject), 295–296 GetDriveName method (FileSystemObject), 297 GetExtensionName method (FileSystemObject), 297–298 GetFile method (FileSystemObject), 298–299 GetFileName method (FileSystemObject), 299–300 GetFolder method (FileSystemObject), 300–301 GetObject function, 78, 358–360 GetParentFolderName method (FileSystemObject), 301 GetSetting function, 361–363 GetSpecialFolder method (FileSystemObject), 302–303 GetTempName method (FileSystemObject), 303 global template file (Word), 12 GlobalMultiUse value (Instancing), 70 GlobalSingleUse value (Instancing), 71 GoSub Return statement, 363–364 Goto statement, 364–365 greater than (>) operator, 607 greater than or equal to (>=) operator, 607 Index VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved H Help button in message boxes, 104 help for VB/VBA, viii HelpContext property (Err), 100, 256–258 HelpFile property (Err), 100, 258–259 Hex, Hex$ functions, 365–366 hexadecimal numbers, 365–366 history of VBA, Hour function, 366 I If Then Else statement, 366–370 #If Then #Else directive, 117–119 IIf function, 370–371 IME (input method editor) IMEStatus function, 371–373 vbIMEStatus type, 601 Immediate window (Debug object), 211–214 Imp operator, 610 Implements statement, 373–375 implicit type conversion, 32 indexes of array elements, 40 information functions (list), 590 Initialize event, 18, 64, 375–376 in-process ActiveX DLLs binding, performance and, 48, 76 creating, 70, 72–75 error handling, 101–104 as out-of-process EXEs, 75 passing variables, 51 registering and unregistering, 75 Sub Main procedure, 19 terminating, 24 Input, Input$, InputB, InputB$ functions, 376–377 Input # Statement, 377–379 input method editor (see IME) InputBox function, 379–381 Instancing property, 70, 381–382 InStr, InStrB functions, 382–383 InstrRev function, 384–385 Int function, 385–386 Integer data type, 28 converting to, 32, 160–161 integer division (\) operator, 606 IntelliSense technology, 80 interactive functions (list), 591 interest payments, 386–388 interest rates, 484–486 internal rate of return, 388–389, 426–427 intrinsic constants, 53, 598–605 enumerated constants vs., 62 inverse tangents, 132–133 IOMode type, 604 IPmt function, 386–388 IRR function, 388–389 Is operator, 607 IsArray function, 389–390 IsDate function, 390 IsEmpty function, 390–391 IsError function, 391–392 IsMissing function, 393 IsNull function, 394 IsNumeric function, 394–395 IsObject function, 395–396 Item method (Collection), 83, 169–171 Item object (Collection), 49 Item property (Dictionary), 227–229 Items method (Dictionary), 229 iterations (see flow control) J Join function, 396–397 K Key property (Dictionary), 229–230 keyboard key presses assigning VB macros to, 15, 17 simulating with SendKeys, 508–511 Keys method (Dictionary), 231 Kill statement, 397–398 L language constants, 601 LastDLLErr property (Err), 100 LastDLLError property (Err), 259–261 last-modification time (files), 279–280 late binding, 48, 76, 78 email within VB (example), 86–88 (see also data binding) launching VB programs, 12–19 Index VB & VBA in a Nutshell: The Language, eMatter Edition Copyright © 2000 O’Reilly & Associates, Inc All rights reserved 625 LBound function, 42, 45, 93, 398–399 LCase, LCase$ functions, 399–400 leading spaces, deleting, 420 Left, Left$, LeftB, LeftB$ functions, 400–401 Len, LenB functions, 401–403 length, file, 280–281, 417–418, 574 length, string, 401–403 less than (