3Outline Key benefits of VBA Preparing for VBA Integration Page 3OutlineKey benefits of VBAPreparing for VBA IntegrationIntegrating VBAWhat is APCVBA Integration ArchitecturePhases of VBA IntegrationThis presentation discusses how to integrate VBA into an application.Preparing for VBA IntegrationBefore beginning a VBA integration, you need to understand the features (or “building blocks”) VBA makes available to real world host applications. Once these features are understood, you will be better able to make the design and architectural decisions required for a successful VBA integration.I’ll also discuss some of the tasks requires to prepare your application for a VBA integration, such as an understanding of COM and object model design.Integrating VBAFinally, I’ll drill down into specific integration tasks (or phases) for VB and C++.
4Outline Key benefits of VBA Preparing for VBA Integration Page 4OutlineKey benefits of VBAPreparing for VBA IntegrationIntegrating VBAWhat is APCVBA Integration ArchitecturePhases of VBA IntegrationThis presentation discusses how to integrate VBA into an application.Preparing for VBA IntegrationBefore beginning a VBA integration, you need to understand the features (or “building blocks”) VBA makes available to real world host applications. Once these features are understood, you will be better able to make the design and architectural decisions required for a successful VBA integration.I’ll also discuss some of the tasks requires to prepare your application for a VBA integration, such as an understanding of COM and object model design.Integrating VBAFinally, I’ll drill down into specific integration tasks (or phases) for VB and C++.
5Visual Basic for Applications Page 5Visual Basic for ApplicationsThe premier development technology found in applications that enables your customers to:CustomizeEnable customers to tailor yourproduct to their specific needsIntegrateEnable customers to create entire line of business solutionsSo what is VBA? VBA, or Visual Basic for Applications, is the premier development technology found in packaged applications. VBA delivers the full power of the Visual Basic programming language along with a rich development environment, intelligent editor, and powerful debugging tools. With VBA, you take this powerful development technology, embed it in to your application, and ship it as an integrated part of your product. By embedding VBA into your products, you greatly expand the possibilities of what your customers can do with your product:First, it enables your customers to customize your application to meet their specific needs. This includes tailoring the look and feel of the application, extending the functionality of the application to handle specialized tasks they require, and automating common tasks that they do on a repeated basis. The big benefit to your customers is that they don’t need to restructure their business process to use your application – Rather, they customize your application to fit perfectly with their business practice.Second, by including VBA in your application, you empower your customers to integrate your application with other VBA-enabled applications, including Office and over 100 third-party products spanning a broad range of industries. In addition, your customers can link your application to legacy corporate information. This allows them to create entire line of business solutions and to be more responsive to changes in their business climate. In effect, VBA enables your customers to use your product not only as a great packaged application, but also as a complete solutions development platform.Third, since VBA uses the Microsoft Visual Basic language your customers can leverage the VB skills they already have. Over 3.2 million developers worldwide are familiar with VB technology, making it the most popular development tool…and if you know VB, you already know VBA. This ensures an ample supply of developer talent for your application customization and integration projects.LeverageDeliver the power of Visual Basic to leverage the 3+ million VB developers
6Buy vs. Build Build Buy Pros Lower Initial Cost Fast Deployment Cons Page 6Buy vs. BuildBuildBuyProsLower Initial Cost Fast DeploymentConsNot FlexibleNo AdvantageProsInfinite Flexibility Your Code & DataConsHigh RiskHigh CostTraditionally there have been two ways to approach solution development: either buy software from a 3rd party vendor or build it yourself from scratch using programming tools like C++ or Visual Basic.Buying “off-the-shelf” software is compelling because it has a lower initial cost when compared to building software from scratch. Furthermore, most software from 3rd party vendors is designed to be easy to deploy, meaning you can get it in the hands of your knowledge workers very quickly.The down side to packaged software, however, is that much of it is inflexible, meaning that it doesn’t meet all your business requirements. Often times this means you settle for less than you want and end up changing your business processes to match the way the software works. In extreme cases this can reduce your competitive advantage if the software doesn’t support a key business process.<click>Building your software from scratch fixes those problems because you can decide exactly how a solution should work. After all, it’s your source code and your data. You can define exactly how every screen looks and how each feature should behave.This doesn’t come without risk or cost, however. Writing software is a complex, time consuming and costly endeavor. It normally requires people who are experts in software development, not necessarily your business. This makes building from scratch very risky because you can’t guarantee you’ll get exactly what you want in a timeframe that works for you. And, besides most companies aren’t in the business of writing software.
7Competitive Advantage! Page 7Buy and CustomizeLower Initial CostInfinite FlexibilityVBA offers the best of both of these worlds through a “buy and customize” alternative. You first find a VBA-enabled product from a 3rd party vendor that meets most of your needs then you use VBA to customize the software to fill in the gaps. You get the benefits of packaged applications because the software is relatively inexpensive and easy to deploy while at the same time gaining the flexibility of software that’s built from scratch. This all contributes to a solution that enables you to retain your competitive advantage.By enabling your customers to augment the core functionality of your application to their individual needs, they’ll gain all the benefits of a “buy and customize” model - Lower Initial Cost, Fast Deployment, Infinite Flexibility, and their solutions are made from their own intellectual property.This translates to a competitive advantage to you.Fast DeploymentYour Code & DataCompetitive Advantage!
8Flexibility Your application becomes a platform Write portions of your application in VBAChange features after you shipAdd features after you shipEliminate one-off feature requestsCreate a 3rd party community
9“Got VBA?” VBA throughout Office 2000 100+ shipping applications Page 9“Got VBA?”VBA throughout Office 2000Outlook, FrontPage100+ shipping applicationsNew announcementsevery weekThere is great momentum of organizations moving to implement VBA as a customization technology. In addition to being included throughout Office 2000 (now including Outlook and FrontPage), VBA is embedded in over 100 third party applications spanning a broad range of industries. These include Accounting, Business Intelligence, CRM, Data Warehousing, Document Management, Engineering, ERP, Financials, GIS, Healthcare, Legal, Manufacturing, etc.More and more organizations are realizing the value of delivering customizable software that can not only be tailored to your customers needs, but also integrated with other VBA-enabled applications to create entire line of business solutions…and we’re announcing more and more VBA licensees every week!
10Types of Applications Traditional “thick client” Multi-threaded applicationsMulti-threaded designerVBA in the Middle-tierAllows customizable business objectsDuwamish sample on MSDNThin clientCheck out the VBA Pavilion!
11DEMO An Application with VBA Page 11 DEMO: Simple host project items Run Microsoft Excel.Double click on a cell. Note how the cursor enters the cell for editing. Type some text in the cell.Write the following code behind Sheet1 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Hello from DoubleClick“ End SubSwitch back to Excel and double-click on the Cell. The dialog appears. Conclusion: The Worksheet COM object (that lives in the windowspace of Excel) is exposed to VBA; VBA, in turn, hooks up to the outgoing interface of the worksheet thereby allowing the VBA user to write code to handle those events.Show the control toolbox and drag a control onto the sheet.Switch back to VBA and display show how the control (on the host project item) is also exposed to VBA in a similar manner.
12Outline Key benefits of VBA Preparing for VBA Integration Integrating VBAWhat is APCVBA Integration ArchitecturePhases of VBA Integration
13Preparing for VBA Integration Page 13Preparing for VBA IntegrationVBA Building BlocksCOM-Enable Your ApplicationDesign and Implement an Object ModelVBA Building Blocks refers to the set of VBA features that a host application can take advantage of -- like projects, project items, and so forth.What are the VBA features that a VBA integrator has to deal with? We’ll explore those quickly in next next few slides.
14VBA Building Blocks… Visual Basic Editor (VBE) Project Explorer Page 14VBA Building Blocks…Visual Basic Editor (VBE)Project ExplorerCode EditorImmediate WindowProperties WindowLocals, Watch, ...VBE Object model“Visual Basic for Application Extensibility”Defined in vbe6ext.olbCodeModule CommandBarEvents VBProject VBComponent References ...The Visual Basic Editor (or “VBE” for short) always appears as a top-level window running in the same process space as your application. Why is this important? Because, like any modeless window in your app, you have to coordinate message traffic to give VBA a chance to intercept the message for itself. Further, interactions with this top-level window need to be coordinated with that of your host application.The VBE serves as the development environment for the VBA developer and, as such, contains all of the tools for creation and debugging of VBA code, such as the code editor, object browser, watch window, and so forth.An interesting UI element of the VBE is the Properties Window, which displays the read/write properties of a COM object. The Properties Window can be hosted outside the VBA IDE. Other UI elements such as the code editor and object browser can only appear within the window space of the VBE.Why is this interesting? Well, the Properties Window is built on top of IDispatch and has nothing really to do with the rest of VBA. You can use it to display the properties of any COM object derived from IDispatch.DEMO: Show Excel, show the VBA IDE, show the Properties Window outside of the VBA IDE.VBA provides programmatic access to the VBE via the Visual Basic Extensibility object model. This gives you control over the menus (known as CommandBars) and other aspects of the VBE. The VBE will be discussed further in the “Advanced VBA Features” presentation.
15VBA Building Blocks... Project Hierarchy VBA Project Project Items Page 15VBA Building Blocks...Project HierarchyVBA ProjectProject ItemsHost project ItemsControls*UserFormsCode modulesClass modulesHost classes**Designers**The overriding architectural principle used by VBA is the project hierarchy.The VBA project contains a number of project items, of which there are 6 types. This snapshot – taken from Microsoft Excel – only shows 4 project items types.Project items contain code.The various types of project items are host project items, UserForms, class modules, code modules, host classes, and designers. We’ll describe these in more detail in a few minutes.* Controls are not visible in the Project Explorer window. They appear only in the Object combo box of the Code Editor** Host Classes and Designers are normally visible in the Project Explorer window, just not this one.
16VBA Building Blocks... VBA Project Unit of persistence Page 16VBA Building Blocks...VBA ProjectUnit of persistenceUses IStorage to load/saveOften, a 1:1 association with documentsAn application can have multiple VBA projectsContains all code in “Project Items”First, lets talk about the VBA project.A VBA Project is the place where the VBA developer writes code. It is made up one or more project items which we talk about later.The VBA project is the fundamental unit of storage. Since it is based on IStorage, you can save the VBA project data to a file, or in memory, thereby allowing you to save the VBA project data to a database or on a server.In Office, there is one VBA project per document, but this doesn’t need to be the case. Many applications use multiple VBA projects per document.Aside from persistence, a VBA project isn’t all that interesting. What is of interest is that it consists of a number of project items that contain VBA code, as described on the next slide.
17VBA Building Blocks... Project Items Host project items Host Classes Page 17VBA Building Blocks...Project ItemsHost project itemsSimply COM objectsExpose events to VBACode “behind” (using COM aggregation)Can have controlsHost ClassesJust like host project items, except that you can have multiple instances of themAs we’ve described, a VBA project consists of a number of project items.What is a project item? In simple terms, a VBA project item is a container for VBA code. There are various types of project items that exhibit different behavior and are therefore used for different purposes. However, the common aspect between all project items is that they contain VBA code.The first type of project item that we’ll examine is the host project item (also called a “document project item”).The host project item is a simple COM object supporting IDispatch and IProvideClassInfo. Like the name suggests, a host project item lives in the host application where it often has a visual representation (like a Document in Microsoft Word). When you expose a COM object to VBA as a host project item, VBA hooks up to the outgoing interface of that object, thereby allowing the VBA user to write code to handle that objects events.
18VBA Building Blocks... Project items... Code module Class module Page 18VBA Building Blocks...Project items...Code moduleContain VBA code onlyGlobalClass moduleCreatable VBA classesUserForms and Other DesignersUserForms (built-in)Can be used to build UI for your applicationVB6 DesignersSome other project items are shown on this slide:A Code Module is simply a place to storage code that has global scope within your VBA project. In Microsoft Word, code modules contain global macros that can be assigned to toolbar buttons, keystrokes, or menu items.A Class Module is like a code module except that you can create instances of it, very much like a C++ class. The subroutines, functions, and variables become methods and properties of that class.A Designer is like a class module except that there is an additional graphical “designer” that accompanies the class module. UserForms are an example of a Designer. You can find additional designers with VB6 and MOD (e.g., DHTML Page, WebClass)
19VBA Building Blocks... Code Execution Macros dialog box Page 19VBA Building Blocks...Code ExecutionMacros dialog boxNamed macros executed in response to UIToolbar, menu selection, keystrokeCan pass parametersEventsCode behindThe last design feature to consider is how code will be executed. What are the various ways that code can be executed?1. Macros dialog box: As you can see in Office, you can execute parameter-less macros from the Macros dialog box.2. Named Macros: You can also execute named macros in response to UI events. In Word, for example, you can assign a macro (by name) to a keystroke.3. Events: With host project items and controls, you’ve seen how you can raise an event and handle it in VBA code, and you’ve also seen how to extend a host object with VBA code (called “code behind”).The VBA programmer can also intercept events of any COM object (that supports it) using the VBA WithEvents statement.4. VBA Classes: VBA classes also represent an interesting way to execute code, as these are “real” COM objects. Using IDispatch, you can execute code in any instance of a VBA class
20Preparing for VBA Integration Page 20Preparing for VBA IntegrationVBA Building BlocksCOM-Enable Your ApplicationDesign and Implement an Object ModelPreparing an application will involve some level of COM support, which we’ll discuss next.
21COM-Enable Your Application Page 21COM-Enable Your ApplicationFollow the COM SpecificationAdopt the COM PhilosophyUse COM as the Binary Standard for Application ComponentsFor MFC applications, use ATL for COM support.Integrating VBA will require some level of COM support in your application. Specifically, you need to create a number of COM objects and expose these objects in your object model.There are many excellent books now about COM, but the COM specification is still the best source for definitive information about how COM works.Adopt the COM PhilosophyYou can also think of COM as a philosophy of software development. There are many books, such as Essential COM, by Don Box, that describe the COM philosophy very well. One of the essential ideas of COM is the idea of an interface, which can be thought of as a contract between a component that exposes a set of services and a client that wants to use the services. By hiding the implementation details inside the component and exposing the functionality by means of an interface, a COM component can offer its services to clients that can be written in any number of different programming languages. By making sure that the interfaces themselves never change, a COM component can guarantee that a client can continue to use its services over multiple versions of the component.Use COM as the Binary Standard for Application ComponentsFinally, COM is a binary standard that allows you to use a variety of programming languages to build components. Any COM client can use the services of a COM-based component without even knowing what programming language was used. Because COM is a binary standard, a COM component can be replaced with a newer version of the component without affecting the clients that use the component.How do you get COM support in your application? The easiest way is to use ATL. For MFC applications, use the peer classes distributed with the VBA6 SDK.
22COM-Enable Your Application... Page 22COM-Enable Your Application...You don’t have to rewrite your applicationUse “peer” objectsApplicationC++ or MFC classesAPCVBAWhen you consider COM-enabling your application, you don’t necessarily have to re-architect your application from scratch. In fact, many existing VBA licensees implement their COM automation layer completely separate from their internal C++ or MFC classes.This allows you to:(1) expose only the functionality you want for external programmability,(2) maintain your currently stable code base.So, although you have to support COM, you don’t have to rewrite everything from scratch.“Peer” COM Objects
23COM-Enable Your Application... Page 23COM-Enable Your Application...VB Applications are COM “friendly”COM object model exposed as VB classesApplicationVB ClassesAPCVBAFor VB developers, VB provides all the COM support you need.The diagram here shows that VB classes can be exposed to VBA.
24Preparing for VBA Integration Page 24Preparing for VBA IntegrationVBA Building BlocksCOM-Enable Your ApplicationDesign and Implement an Object ModelThe last step in preparing your application for VBA integration is to design and implement an object model. Much of this work in designing an object model can happen in parallel with VBA integration, but it is important to recognize that this is a separate task, not specifically related to the integration of VBA. It is true that the primary consumers of your object model will be VBA, so it is important to design your object model with the VBA user in mind.Obviously an object model allows your application to be driven externally from other COM consumers like VB applications but VBA is in process and therefore:1) Faster.2) Part of your application's solution not a third party add-on.3) Makes hooking up events easier.
25Design and Implement an Object Model Page 25Design and Implement an Object ModelDefinition: An Object Model is the set of objects, methods, and properties your application exposes for programmabilityRequired for VBA integrationWhat is an object model?Simply put, an object model is the set of objects, methods, and properties your application exposes for programmability. An object model is implemented using COM and described in your application’s type library (or IDL file).Your application must have an object model of some sort for VBA integration. If you think about it, VBA is only interesting in that it makes available the unique functionality of your application. Considering the overall task of integrating VBA into an application, creating a useful object model is 90% of the work. The actual code you write to integrate VBA is almost trivial in comparison.How do you design an object model? What guidelines do you follow? These are described in the Object Model Design document that I have prepared and included in your handouts. There is also a 1-hour presentation later in the day.
26Why Expose an Object Model? Allow your application to be part of bigger solutionsCan be driven by a wide variety of tools (VBA, VB, VC++, Delphi, and others)Create a 3rd party community supporting your productRequired for VBA integration
27Object Model Design Tips Use standard constructs and behaviorUsers will already know it.Users will intuitively understand it.VBA will not choke on it.Events provideRespond to user actionsRespond to detected conditionsHook application internalsSee the Summit white paper
28DEMO Object Model Page 28 DEMO: Simple host project items Run Microsoft Excel.Double click on a cell. Note how the cursor enters the cell for editing. Type some text in the cell.Write the following code behind Sheet1 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Hello from DoubleClick“ End SubSwitch back to Excel and double-click on the Cell. The dialog appears. Conclusion: The Worksheet COM object (that lives in the windowspace of Excel) is exposed to VBA; VBA, in turn, hooks up to the outgoing interface of the worksheet thereby allowing the VBA user to write code to handle those events.Show the control toolbox and drag a control onto the sheet.Switch back to VBA and display show how the control (on the host project item) is also exposed to VBA in a similar manner.
29Outline Key benefits of VBA Preparing for VBA Integration Integrating VBAWhat is APCVBA Integration ArchitecturePhases of VBA Integration
30Q: How do you integrate VBA? Page 30Integrating VBAQ: How do you integrate VBA?A: Use Microsoft APC. Application Programmability Component!?Question: So how do you integrate VBA? <CLICK>Answer: Use Microsoft APC.Use APC
31What is APC? APC Application Programmability Component Page 31What is APC?APC Application Programmability ComponentCOM object with interfaces used to host VBA (IApc*)Can be used from most COM consumers (VB, MFC, ATL, C++, Delphi, etc.)APC stands for “Application Programmability Component” and is a COM component that exposes a set of interfaces used to integrate VBA into an application. Each of the interfaces begin with “IApc”.APC can be used from nearly any COM consumer -- it simply requires that the user be able to make COM calls. Many popular development platforms can be used with APC.
32What is Required for Your Application to use APC? Page 32What is Required for Your Application to use APC?Must be able to call COM interfacesMust sink COM source interfacesIf your application needs to show the VBA Editor……it must provide access to its message loopIn order to use APC, the host must:Make calls on COM interfaces. VB, Delphi, and C++ applications are certainly capable of doing this.2. Provide a sink for COM source interfaces. APC will advise on certain predefined interfaces; in order to catch these notifications, the host application needs to be able to provide a sink for these COM interfaces.3. Modify the message loop and coordinate certain window messages with VBA.The last requirement is particularly nasty, as many development environments don’t have access to the message loops. For example, an application written in PowerBuilder doesn’t have access to the message loop. Same thing with using a Web browser as a client.In scenarios with a hidden message loop, you can still run VBA code, you just can’t show the VBA IDE or show modeless dialogs. There are two alternatives:1. You can host VBA out of process.or2. You can create a separate development environment and runtime.
33VBA Integration Architecture Page 33VBA Integration ArchitectureMFCC++VBDelphi …Application CodeAPC/C++ (CApc*)APC/MFCTemplate CodeAPC COM Component (IApc)Integration Code1. The green box shows the core VBA components. <CLICK>2. The blue bubbles show the various development platforms. (The Delphi bubble contains ellipses to show that other development environments are possible as well.)How do you connect together the apps (in blue) with VBA (in green)? <CLICK>3. Use APC, as shown in orange. <CLICK>4. Many environments can use the APC component directly, <CLICK> such as VB and <CLICK> Delphi. C++ <CLICK> and MFC can use it directly as well.5. Despite the fact that C++ and MFC programs can use the APC COM component directly, APC provides a set of template-based classes to make integration even easier. <CLICK> The red boxes show the APC frameworks, which are built on top of the APC COM component.6. <CLICK> The C++ developer uses the APC/C++ classes...7. <CLICK> …and the MFC developer uses the APC/MFC classes.Microsoft VBA (IVba*)Core VBA Code
34APC Object Model (Simplified) Page 34APC Object Model (Simplified)ObjectApcProjectProjectsCollectionProjectItemProjectItemsControlControlsHost Project ItemCode ModuleClass ModuleThe APC COM component exposes an object model -- these objects are what your host application uses to integrate VBA. You have a complete object model diagram for APC in your handouts (the poster) -- the above diagram is a simplification of that diagram.The primary object for VBA integration is the Apc object. This co-creatable object provides access to all VBA hosting features.<CLICK> Off the Apc object is the Projects collection which contains zero or more VBA projects, each represented by the APC Project object.<CLICK> Each project contains a collection of ProjectItem objects called ProjectItems. The various types of project items are represented in the diagram, including host project items, code modules, class modules, user forms, host classes, and designer items.<CLICK> A special type of project item -- i.e., the host project item – can contain zero or more controls -- represented in the above diagram by the Controls collection.Designer ItemUserFormHost Class
35VBA Integration Tasks Phase 1: Initial Steps Phase 2: Projects Page 35VBA Integration TasksPhase 1: Initial StepsSimplePhase 2: ProjectsModerateComplexSTOPPhase 3: (Optional) Project ItemsSTOPPhase 4: (Optional) ControlsNext I’ll talk about the various phases of VBA integration.Obviously, every integration is different. These phases serve more to illustrate how an integration proceeds through the VBA features, starting with the base features and on to the more advanced features.<CLICK> The first two phases are required for every VBA integration; later phases build upon these. Phases <CLICK> 3 and <CLICK> 4 are optional, require more work, but present a more complete VBA programming environment for the VBA user.In a later presentation, we’ll discuss “advanced features”, which, for the most part, can be added after each of the above phases.STOPNote: Advanced Features can be added to any completed VBA integration project.
36Phase 1: Initial Steps Initializing APC Create the APC HostAssociate the Application ObjectManage windows and eventsShow the VBA IDE
37Phase 1: Initial Steps Initializing APC Page 37Phase 1: Initial Steps Initializing APCWhat is the Application object?Merges methods & properties into namespaceSub Main MsgBox “Hello” r = Application.Foo r = Foo End SubMsgBox is a VBA built-in keywordAnother task for the first phase of VBA integration involves exposing your Application object -- the top-level object in your application’s object model -- to VBA. The Application object is the object marked with the ‘appobject’ attribute in your application’s IDL file. The methods and properties of this top-level object are merged into the global namespace of VBA.In the example, the Application object exposes a method called “Foo”. As demonstrated, the method “Foo” can be called just like VBA’s built-in MsgBox statement -- both are top-level keywords in the VBA namespace.Setting the application is simply – simply pass the IDispatch interface of your Application object to APC by calling IApc::put_ApplicationObject.Foo is a method of the Application objectFoo is merged into VBA’s global namespace and can be called without further qualification
38Phase 1: Initial Steps Managing windows and events Page 38Phase 1: Initial Steps Managing windows and eventsVBA IDE is a top-level windowWindow parentingTracking the active componentForward accelerators to active componentRe-entrant message loopIsolate to a single set of routinesVBA is an in-process component that adds an independent, modeless, top-level window to the host application. For this to work seamlessly, the host needs to:1. Support message-loop processing2. Support idle-time processing3. Provide state notifications4. Provide activation notificationsThe most difficult part of this for existing applications is isolating your message loop to a singe routine and making it re-entrant. When VBA displays a modal dialog (such as a user form), a message loop is “pushed”, thereby re-entering your message loop. It is possible (and even common) for a few message loops to be pushed (e.g., while debugging a user form).Again, for VB applications, APC handles integrates the message and idle processing of the VB application into VBA.[In case somebody asks]How does this work? It uses some magic called the MSO component manager – a piece of VBA that actually comes from Microsoft Office. The component manager implements a set of interfaces that manage the UI of various COM components, each of which can be active with the focus. If you have ever tried to display a modeless dialog from a VB ActiveX DLL in a non-Office application, you’ll know what it means to *not* have a component manager.To track the active component and coordinate your message and event activity with VBA, your host application must implement the IApcSite -- VBA will call this site for various notifications (pushing a message loop, entering a modal state, and so on). In response to these notifications and some window messages, your application calls into the IApcCompManager interface to let VBA know, for example, that it is being activated.Sounds complicated? Well, the APC frameworks that we’ll discuss later handle much of the complexity for you.VB Programmer doesn't have to worry about all this. APC integrates the message loop of your VB application into that required by VBA automatically.
39DEMO Phase 1: Initial steps Page 39 4) The last task for a phase 1 integration is showing the VBA IDE. This is easily accomplished by setting the Visible property of the IApcIde object to true.When you complete phase 1, you will be able to show the VBA IDE (with all window coordination handled properly), show the VBA IDE, and verify that your window/event coordination is handled properly. However, you cannot yet write any code, as you don’t have a VBA project in which to place the code -- we do that in phase 2.
40Phase 2: Projects Project is the unit of persistence Page 40Phase 2: ProjectsProject is the unit of persistenceCreate, Save, Load a ProjectExecute codeAn application can have multiple VBA projectsIn the second phase of integration involves creation of a VBA project. When adding a project, you need to decide:1. What does the VBA project represent to the end user?2. Do you need more than one VBA project (e.g., a global template, like Word)?3. Where will the VBA project be stored? In a document or a database?4. How will the project be stored?I’ll describe these in the next few slides.A VBA project is added by calling IApcProjects::Add.Once you have a VBA project, the VBA user will be able to write VBA code against your application’s object model.
41Phase 2: Projects Persistence Page 41Phase 2: Projects PersistenceRequires OLE structured storage (IStorage)Disk-basedIn your document fileIn standalone fileIn-memoryStored in a database as a BLOBMust be transactedIApcProject supports IPersistStorageFor VB Developers, APC supports:Storage ObjectStream ObjectVBA requires that the host implement an IStorage in which to save the VBA project. If you already use OLE structured storage for your application’s own internal data format, then you’re all set – simply create a transacted substorage and hand it off to VBA. If you don’t use OLE structured storage, then you can save the VBA project into a separate stand-alone file, or use an in-memory storage and save the bytes to your own file format.In-memory storages are particularly interesting, as they allow you to save VBA into a database.For the C++ programmer, the Project object supports IPersistStorage, thereby allowing you to easily store the VBA project in the storage of a parent in-place activated app, or along with the serialized MFC storage.For the VB developer, APC contains an implementation of a Storage and Stream objects that you can use for saving the VBA project.
42Phase 2: Projects Executing VBA code Page 42Phase 2: Projects Executing VBA codeNamed macros -- use the Run methodTheProject.Run "ThisDocument", "Main"Available for ProjectItem, Procedure, and ProjectIApcProjectItem::RunIApcProcedure::RunIApcProject::RunMacros dialog...Dim TheScopes As MSAPC.ScopesSet TheScopes = TheProject.CreateScopesTheScopes.MacrosDialog.ShowIf the VBA user writes code, how will your application execute it? Of course, the user can always execute code from the VBA IDE (by hitting the Start button, for example). But that isn’t tightly integrated with the host application.As we described earlier, there are a few ways that you can execute code.To execute a named macro, use the Run method off the Project, ProjectItem, or Procedure objects. Microsoft Word allows you to customize the toolbar, menu, and keyboard by executing a named macro in this manner.
43Phase 2: Projects Other uses Page 43Phase 2: Projects Other usesCode sharing / reuseMicrosoft Word templates (NORMAL.DOT)Global libraryCustom event routingEvent goes first to main host project itemIf event not handled, routes to templateThe VBA project, as we have repeated many times so far, is the unit of storage, the holder of projects items which, in turn hold VBA code.VBA projects can be used for other purposes. For example, Microsoft Word creates a VBA project in the document template. When an event is fired to the Document, it is also fired to the template, thereby allowing the VBA user to handle the events in either or both places.Why do this? It allows the VBA programmer to share code between many documents. The host application accomplishes this using two VBA projects and routing the event appropriately to the host project items exposed in each of those VBA projects.
44DEMO Phase 2: Projects Page 44 DEMO: Simple host project items Run Microsoft Excel.Double click on a cell. Note how the cursor enters the cell for editing. Type some text in the cell.Write the following code behind Sheet1 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Hello from DoubleClick“ End SubSwitch back to Excel and double-click on the Cell. The dialog appears. Conclusion: The Worksheet COM object (that lives in the windowspace of Excel) is exposed to VBA; VBA, in turn, hooks up to the outgoing interface of the worksheet thereby allowing the VBA user to write code to handle those events.Show the control toolbox and drag a control onto the sheet.Switch back to VBA and display show how the control (on the host project item) is also exposed to VBA in a similar manner.
45Phase 3: Project ItemsUsed to expose an object in your COM object model’s hierarchyVBA user can write VBA code to handle eventsVBA user can write code behind
46Phase 3: Project Items Host project items are simply COM objects Page 46Phase 3: Project ItemsHost project items are simply COM objectsMust derive from IDispatch and support IProvideClassInfoMethod’s parameters strongly typed and namedCoclass exposes a source interface (events)The next phase involves adding a host project item. As I described earlier, from a technical perspective, a host project item is just a COM object (supporting IDispatch and IProvideClassInfo) that is exposed to VBA. As a host project item, VBA hooks up to the outgoing interface of the object – so you must have a coclass that supports both an inconoming and outgoing interface.You can expose any object in your application’s object to VBA as a host project item as long as it meets this criteria.Once you’ve exposed a COM object to VBA (and allow VBA to hook up the events), the VBA user can write code to handle those events. Further, any additional VBA subroutines actually extend your host object (VBA uses COM aggregation to accomplish this).The name of the host project items in your VBA project become top-level keywords to VBA. Further, in the code module for the host project item, the methods and properties of that interface are top-level keywords to VBA.
47Phase 4: Controls VBA controls are simply COM objects Types Page 47Phase 4: ControlsVBA controls are simply COM objectsTypesBuilt-in COM objectsExternal ActiveX controls (.OCX)Placed in the VBA hierarchy on a host project itemControl name merged into namespaceThe next phase involves adding a control to the host project item. If your application is a container of some sort and that container is exposed to VBA as a host project item, then you have the option of creating controls on that host project item.VBA supports two types of controls -- built-in control and external. External controls are simply those whose type information is external to that of the host application. They don’t have to be full blown ActiveX controls, but they usually are.A control to VBA is simply a COM object logically situated on a host project item. Not only are they logically situated on the host project item, but the names of the controls on are dynamically added as properties to the host project item. VBA sinks to the outgoing interfaces of controls, thereby allowing the VBA user to write code to handle the events of the controls. (Just like with a host project item.)You can add controls for a variety of reasons – you don’t have to implement a control container or host external controls to use this feature.One interesting aspect of a control is that the host can provide an extender object containing methods and properties specific to that control’s container. For example, in a form, your extender might contain positional properties for each control in that container.DEMORun iGrafxCreate a Basic DiagramShow the VBA IDE and show the various controls on ThisDiagram.
48DEMO Phases 3 & 4: Project Items and Controls Page 48 DEMO: Simple host project itemsRun Microsoft Excel.Double click on a cell. Note how the cursor enters the cell for editing. Type some text in the cell.Write the following code behind Sheet1 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Hello from DoubleClick“ End SubSwitch back to Excel and double-click on the Cell. The dialog appears. Conclusion: The Worksheet COM object (that lives in the windowspace of Excel) is exposed to VBA; VBA, in turn, hooks up to the outgoing interface of the worksheet thereby allowing the VBA user to write code to handle those events.Show the control toolbox and drag a control onto the sheet.Switch back to VBA and display show how the control (on the host project item) is also exposed to VBA in a similar manner.
49VBA Integration Phases: Summary Page 49Phase 1: Initial StepsPhase 2: ProjectsPhase 3: (Optional) Project ItemsVBA Integration Phases: SummaryPhase 4: (Optional) ControlsSimpleModerateComplexSTOPWe have now completed the various phases of VBA integration including ininitialization, creating projects and project items, and adding controls. Where do you go from here?<CLICK> There are many more features offered by VBA which we have called “Advanced Features”. They can be added to any VBA-enabled application regardless of whether you support host project items or controls.Note: Advanced Features can be added to any completed VBA integration project.
50Advanced VBA Features VBA Extensibility Object Model Page 50Advanced VBA FeaturesVBA Extensibility Object ModelDigital SignaturesCOM Add-insActiveX Designers<CLICK> VBA Extensibility Object Model: The VBE can be used for a variety of tasks, including customizing the VBA IDE and adding inter-project references.<CLICK> Digital Signatures: You can sign a VBA project to ensure that it is from a trusted source. Uses IE digital signature technology.<CLICK> COM Add-Ins: You can create VBA COM add-ins (that implement the IDTExtensibility2 interface) and host these add-ins in the VBA IDE. VBA also offers add-in services that allow you to host COM add-ins in your application.<CLICK> ActiveX Designers: VBA allows you to insert (as a project item) any ActiveX Designer. The VBA programmer can then write code to handle the events generated by the AxD.These features will be described in detail in a presentation later today.
51DEMO Advanced Features Page 51 DEMO: Simple host project items Run Microsoft Excel.Double click on a cell. Note how the cursor enters the cell for editing. Type some text in the cell.Write the following code behind Sheet1 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Hello from DoubleClick“ End SubSwitch back to Excel and double-click on the Cell. The dialog appears. Conclusion: The Worksheet COM object (that lives in the windowspace of Excel) is exposed to VBA; VBA, in turn, hooks up to the outgoing interface of the worksheet thereby allowing the VBA user to write code to handle those events.Show the control toolbox and drag a control onto the sheet.Switch back to VBA and display show how the control (on the host project item) is also exposed to VBA in a similar manner.
52Outline Key benefits of VBA Preparing for VBA Integration Integrating VBAWhat is APCVBA Integration ArchitecturePhases of VBA Integration
53For more information… http://msdn.microsoft.com/vba