Fandom

Microsoft Wikia

Visual Basic for Applications

860pages on
this wiki
Add New Page
Talk0 Share

Template:Peacock

Visual Basic for Applications (VBA) is an implementation of Microsoft's event-driven programming language Visual Basic 6, and associated integrated development environment (IDE), which is built into most Microsoft Office applications. VBA enables developers to build user defined functions, automate processes, and access Win32 and other low level functionality through DLLs. It was also built into Office applications up to version 2004 for Apple's Mac OS X, other Microsoft applications such as Microsoft MapPoint and Microsoft Visio; as well as being at least partially implemented in some other applications such as AutoCAD, WordPerfect and ArcGIS. It supersedes and expands on the capabilities of earlier application-specific macro programming languages such as Word's WordBasic, and can be used to control many aspects of the host application, including manipulating user interface features, such as menus and toolbars, and working with custom user forms or dialog boxes. VBA can also be used to create import and export filters for various file formats, such as ODF.

As its name suggests, VBA is closely related to Visual Basic and uses the Visual Basic Runtime, but can normally only run code within a host application rather than as a standalone application. It can, however, be used to control one application from another using OLE Automation. For example, it is used to automatically create a Word report from Excel data, in turn automatically collected by Excel from polled observation sensors. The VBA IDE is reached from within an Office document by pressing the key sequence <Alt>F11.

VBA is functionally rich and flexible but it does have some important limitations, such as restricted support for function pointers which are used as callback functions in the Windows API. It has the ability to use (but not create) (ActiveX/COM) DLLs, and later versions add support for class modules.

Language

Code written in VBA is compiled[1] to a proprietary intermediate language called P-code (packed code)[2], which is stored by the hosting applications (Access, Excel, Word, PowerPoint)) as a separate stream in structured storage files (e.g., .doc or .xls) independent of the document streams. The intermediate code is then executed[1] by a virtual machine (hosted by the hosting application). Despite its resemblance to many old BASIC dialects (particularly Microsoft BASIC, from which it is indirectly derived), VBA is not compatible with any of them except Microsoft Visual Basic, where source-code of VBA Modules and Classes can be directly imported, and which shares the same library and virtual machine. Compatibility ends with Visual Basic version 6; VBA is not compatible with VB.NET. VBA is proprietary to Microsoft and, apart from the COM interface, is not an open standard.

Object models

To use VBA with an application such as Access, Word, or Excel, terminology and language constructions are needed to interact with the application.[3][4] This portion of VBA is called the Object Model for the application. A map of the object model is online for Excel and for Word. A listing of the object model is found by opening the Macro/VBA editor in the target application and then using "View" to open the "Object Browser" (F2).

Much of the difficulty in using VBA is related to learning the object model, which uses names invented by the originators of the model that may be less than transparent to a new user. One way to learn the terms and syntax of the object model is to use the macro recorder to record the steps taken to achieve a desired result using the mouse and menus of the application.[5] Once this is done, the VBA code constructed by the recorder can be viewed in the VBA editor, and often greatly streamlined or generalized with only a modicum of understanding of VBA itself. Unfortunately, the macro recorder does not always record everything (particularly for graphs), and some applications employing VBA do not provide a recorder at all. Use of debugging tools to discover VBA constructs for some cases where the macro recorder does not work are described by Jelen and Syrstad,[6] but some steps may remain obscure.

A more complete description of the strengths and weaknesses of the Visual Basic language is found in Visual Basic.

Automation

Interaction with the host application uses OLE Automation. Typically, the host application provides a type library and API documentation which document how VBA programs can interact with the application. This documentation can be examined from inside the VBA development environment using its Object Browser.

VBA programs which are written to use the OLE Automation interface of one application cannot be used to automate a different application, even if that application hosts the Visual Basic runtime, because the OLE Automation interfaces will be different. For example, a VBA program written to automate Microsoft Word cannot be used with a different word processor, even if that word processor hosts VBA.

Conversely, multiple applications can be automated from the one host by creating Application objects within the VBA code. References to the different libraries must be created within the VBA client before any of the methods, objects, etc. become available to use in the application. These application objects create the OLE link to the application when they are first created. Commands to the different applications must be done explicitly through these application objects in order to work correctly.

For example: In Microsoft Access, users automatically have access to the Access library. References to the Excel, Word, and Microsoft Outlook libraries can also be created. This will allow creating an application that runs a query in Access, exports the results to Excel, formats the text, then writes a Mail merge document in Word that it automatically e-mails to each member of the original query through Outlook. (In this example, Microsoft Outlook contains a security feature that forces a user to allow, disallow, or cancel an e-mail being sent through an automated process with a forced 5 second wait. Information on this can be found at the Microsoft website.)

VBA programs can be attached to a menu button, a macro, a keyboard shortcut, or an OLE/COM event, such as the opening of a document in the application. The language also provides a user interface in the form of UserForms, which can host ActiveX controls for added functionality.

Security concerns

Like any common programming language, VBA macros can be created with a malicious intent. Using VBA, most of the security features lie in the hands of the user, not the author. The VBA 'host-application' options are accessible to the user. The user who runs any document containing VBA macros can preset the software with user preferences, much like those for internet browsers. End-users can protect themselves from attack by disabling macros from running in an application if they do not intend to use documents containing them, or only grant permission for a document to run VBA code if they are sure the source of the document can be trusted.

Named variables and user-defined functions

File:Named Variables in Excel.PNG
File:Functions in Excel.PNG

A common use of VBA is to add functionality that may be missing from the standard user interface. Use of VBA is made much easier by using named variables on the spreadsheet, as shown at the left. The formula for y=x2 resembles Fortran or Basic, and the Name Manager shows the definitions of column variables y and x.

Using VBA, the user can add their own functions and subroutines that refer to these named ranges. In the figure at the right, the function sq is created in the Visual Basic editor supplied with Excel, and x & y are named variables in the spreadsheet.

Subroutines

File:Subroutine in Excel.PNG

Functions themselves cannot write into the worksheet, but simply return their evaluation. However, in Microsoft Excel, subroutines can write values or text found within the subroutine directly to the spreadsheet. The figure shows the Visual Basic code for a subroutine that reads each member of the x-column (named column variable x), calculates its square, and writes this value into the corresponding y-column (also a named column variable). The y-column contains no formula because its values are calculated in the subroutine and simply written in.

Examples

This macro provides a shortcut for entering the current date in Word:

Sub EnterCurrentDate()
    Selection.InsertDateTime DateTimeFormat:="dd-MM-yy", InsertAsField:=False, _
         DateLanguage:=wdEnglishAUS, CalendarType:=wdCalendarWestern, _
         InsertAsFullWidth:=False
End Sub

VBA is useful for automating database tasks such as traversing a table:

Sub LoopTableExample
 
    Dim db As DAO.Database
    Dim rs As DAO.Recordset
 
    Set db = CurrentDb
    Set rs = db.OpenRecordset("select columnA, columnB from tableA")
 
    Do Until rs.EOF
         MsgBox rs!columnA & " " & rs!columnB
         rs.MoveNext
    Loop
 
    rs.Close
    Set db = Nothing
End Sub

VBA is useful for automating repeated actions in rows of a spreadsheet. For example, using the following code example, the built-in iterative solver Goal Seek is applied automatically to each row in a column array, avoiding repeated use of manual menu entry. Below a column variable "C_M" determines the values of another column variable "Target" in some nonlinear fashion. The built-in nonlinear solver Goal Seek is called to find the value of "C_M" that brings "Target" to value one. The subroutine is inserted into the workbook using the VBA editor and command Insert Module. It is called directly from the VBA editor, or by using a "hot key" or keyboard shortcut. Values on the spreadsheet automatically update as the rows are scanned.

It is useful to note that subroutines have the power to update variables on the spreadsheet; functions do not - they simply report their evaluation.

Line Option Explicit is not part of the subroutine: it sets a compiler option that forces identification of all variables that have not been specified in Dim statements, which avoids difficult to detect debugging problems caused by typos. Notation ( ' ) in the following code denotes a comment, and ( _) line continuation. The code uses NAMED variables: a form of cell reference in which cells are assigned names of user choice, rather than the standard cell designation referring to specific row and column numbers. Naming is accomplished on the worksheet using the Excel "Name Manager", or menu Insert Name: Create.

Option Explicit
 
Sub SetTarget()
'
' SetTarget Macro
'
   Dim J As Integer
   Dim Size As Integer
'
' On the spreadsheet, array "C_M" is a NAMED column variable
'     Its members use a row index taken as J
' Built-in function COUNT determines size of array "C_M"
'
   Size = Range("C_M").Cells.Count
'
' Set initial value of all members of array 
'    C_M to 1E-06; J = row index
'
       For J = 1 To Size
           Range("C_M").Cells(J) = 0.000001
       Next J
'
' "Target" is another NAMED array on the spreadsheet of 
'      dimension "Size"; the same size as array "C_M"
'
' Each "Target" entry in each row depends in a
'      specified way upon the value of "C_M" in that row, 
'      for example, by a function such as: Target = C_M*C_M 
'
' GOAL SEEK is a built-in iterative solver in Excel
'
' Call GOAL SEEK to set each "Target" member to unity: for example,
'   taking J = row index, in row J the cell named "C_M" is changed 
'   by GOAL SEEK until "Target" in row J is one
'
' Syntax (aside from "for-next" details) found with macro recorder;
'      underscore "_" is line continuation
'
       For J = 1 To Size
           Range("Target").Cells(J).GoalSeek Goal := 1, _
             ChangingCell := Range("C_M").Cells(J)
       Next J
End Sub

In the example below VBA is used to get an array from a cell range, manipulate the array, and then set the values back in a different range. This works many times faster than directly setting the cell values one-by-one.

Sub CalculateSquares(rinput As Range, routput As Range)
   'Variable specifications
    Dim values() As Variant
    Dim i As Integer, N As Integer
 
    'Count the rows to compute
    N = rinput.Rows.Count
 
    'Set values array from input range.
    'Expected shape of array is (1 to N, 1 to 1)
    values = rinput.Value
 
    'Iterate through rows and set values
    For i = 1 To N
        values(i, 1) = values(i, 1) ^ 2
    Next i
 
    'Export values back into the spreadsheet by setting the
    'value property of the output range.
    routput.Value = values
 
End Sub

VBA can be used to create a user defined function (UDF) for use in a Microsoft Excel workbook:

Public Function BusinessDayPrior(dt As Date) As Date
 
    Select Case Weekday(dt, vbMonday)
        Case 1
            BusinessDayPrior = dt - 3      'Monday becomes Friday
        Case 7
            BusinessDayPrior = dt - 2      'Sunday becomes Friday
        Case Else
            BusinessDayPrior = dt - 1      'All other days become previous day
    End Select
End Function

Example of how to add an external application object (the user must have the application library referenced in the application before this):

Public Sub Example()
    Dim XLApp As Excel.Application
    Dim WDApp As Word.Application
 
    Set XLApp = CreateObject("Excel.Application")
    Set WDApp = CreateObject("Word.Application")
 
    ' ...your code here...

    XLApp.Quit
    WDApp.Quit
 
    Set XLApp = Nothing
    Set WDApp = Nothing
End Sub

Future

As of July 1, 2007, Microsoft no longer offers VBA distribution licenses to new customers.[7] Microsoft intended to add .NET-based languages to the current version of VBA ever since the release of the .NET Framework.[8] The .NET Framework versions 1.0 and 1.1 included a scripting runtime technology known as Script for the .NET Framework.[9] Also, Visual Studio .NET 2002 and 2003 SDK contained a separate scripting IDE called Visual Studio for Applications (VSA) that supported VB.NET.[10][11][12] One of its significant features was that the interfaces to the technology were also available via Active Scripting (VBScript and JScript), allowing even .NET-unaware applications to be scripted using .NET languages. However, VSA was deprecated in version 2.0 of the .NET Framework,[12] leaving no clear upgrade path for applications desiring Active Scripting support (although "scripts" can be created in C#, VBScript, and other .NET languages, which can be compiled and executed at run-time via libraries installed as part of the standard .NET runtime).

Support for VBA in the Mac OS X version of Microsoft Office was dropped with the release of Microsoft Office 2008 for Mac.[13][14]. The official reason given was that VBA relied heavily on machine code written for the PowerPC architecture, and that rewriting this code for dual PowerPC/Intel architectures would have added another 2 years to the development of the suite. However, the office suite can be automated using AppleScript to an extent. In a press statement released on May 13, 2008, Microsoft's Macintosh Business Unit (Mac BU) announced that VBA will be returning in the next version of Office for Mac[15], and Microsoft's announcement of Microsoft Office 2011 for Mac on February 11, 2010 confirmed this promise would be delivered upon[16][17]. Microsoft has also clearly stated that they have no plans to remove VBA from the Windows version of Office.[18][19]

After a decade of neglect, Microsoft has announced that VBA will at last be upgraded to 64 bits, as well as as other improvements. This will break compatibility in some cases, such as calls to the 32 bit Windows API, though this is trivial to fix. [20]

Visual Studio Tools for Applications (VSTA)

With the release of Visual Studio 2005, Microsoft announced Visual Studio Tools for Applications (VSTA). Independent Software Vendors may license VSTA in order to provide their end-users with customisation facilities within their application, in a similar way to VBA, however VSTA uses the Visual Studio 2005 or Visual Studio 2008 development environment for programming against the .NET Framework.

VSTA was included in Office 2007 particularly for adding custom program code to InfoPath forms. An introduction to its use is provided by Microsoft.

See also

References

  1. 1.0 1.1 ACC: Visual/Access Basic Is Both a Compiler and an Interpreter
  2. Microsoft P-Code technology
  3. Steven Roman (2002). Writing Excel Macros with VBA. Sebastopol CA: O'Reilly. Chapter 15. ISBN 0596003595. http://books.google.com/books?id=m4_8FNfla0kC&pg=PA183&dq=%22Excel+Object+model%22&as_brr=0&sig=vTT65wWusbHIDyyNFY7CyN6Kjow#PPA183,M1. 
  4. Steven Roman (1999). Writing Word Macros. Sebastopol CA: O'Reilly. Chapter 10. ISBN 1565927257. http://books.google.com/books?id=C7oZZMt9sqkC&pg=RA1-PA128&dq=%22Word+Object+model%22&as_brr=0&sig=ate-q1wP39TycANqGVHvvWHlRH8. 
  5. Matthew MacDonald (2005). Excel: The Missing Manual. Sebastopol CA: O'Reilly. pp. 655. ISBN 0596006640. http://books.google.com/books?id=1TwjdmRI59AC&pg=PA655&dq=Excel+%22macro+recorder%22&as_brr=0&sig=u2h-Y8fQbtmXZIc7p-SlNBaW-SI. 
  6. Jelen, B., & Syrstad, T. (2008). VBA and macros for Microsoft Office Excel 2007 (business solutions) (Second edition ed.). Indianapolis, Ind: Que. Chapter 2; pp. 42–52. ISBN 0789736829. http://www.amazon.com/gp/reader/0789736829/ref=sib_dp_pt/104-3686210-0230303#reader-link. 
  7. Discontinuation of the VBA Licensing Program
  8. Visual Studio for Applications
  9. Introducing Visual Studio for Applications
  10. Script happens .NET: MSDN
  11. Microsoft Takes Wraps Off VSA Development Technology
  12. 12.0 12.1 VSA scripting in .NET
  13. "WWDC: Microsoft updates Universal status of Mac apps". Macworld. 2006-08-07. http://www.macworld.com/news/2006/08/07/msuniversal/index.php. Retrieved 2007-05-25. 
  14. Office 2008 without VBA
  15. Microsoft Mac BU Delivers Strongest Launch in History of Office for Mac: Group releases Service Pack 1, announces the return of Visual Basic for Applications in next version
  16. "Microsoft will bring back macros to Mac Office in 2011". http://www.computerworld.com/s/article/9085678/Microsoft_will_bring_back_macros_to_Mac_Office_in_2011. Retrieved 2010-04-21. 
  17. "Microsoft to bring back Visual Basic in Office for Mac". http://www.macworld.com/article/133393/2008/05/vba.html. Retrieved 2010-04-21. 
  18. The Reports of VBA's Demise Have Been Greatly Exaggerated
  19. Clarification on VBA Support
  20. http://blogs.msdn.com/excel/archive/2010/01/27/programmability-improvements-in-excel-2010.aspx

External links

HistoryWebsiteMicrosoft Product ActivationGenuine Advantage
Windows
3.095972000XP20032007201020132016
Mac OS/OS X
982001X200420112016
Applications (List)
Desktop
AccessExcel (Viewer)InfoPathLyncOneNoteOutlook (Outlook ConnectorAdd-ins)• PowerPoint Viewer) • ProjectPublisherMicrosoft SharePoint (DesignerWorkspace)</small> • VisioWord • (Viewer)</small>
Server
Forms ServerGroove ServerLync ServerPerformancePoint ServerProject ServerProject Portfolio ServerSharePoint ServerExcel ServicesInfoPath Forms Services
Mobile
Office Mobile
Online
Live MeetingOffice LiveOffice Web AppsOutlook Web AppOffice 365Outlook.com
Office tools
Microsoft Office shared toolsRibbon HeroRibbon Hero 2
Discontinued
AccountingDocument ImagingEntourageFrontPageMicrosoft InterConnectLiquid MotionMailOffice AssistantsMicrosoft PhotoDrawPhoto EditorSchedule+Snapshot Viewer for AccessMicrosoft Vizact
Related products
WorksMapPointSearch ServerLanguage Packs
Technologies
Information Bridge FrameworkObject Linking and EmbeddingOffice Open XMLOffice XML formatsSmart tagsVisual Basic for Applications
  1. REDIRECT Template:Microsoft development toolsaf:VBA

ar:فيجوال بيسك للتطبيقات bs:Microsoft VBA bg:Visual Basic for Applications da:Visual Basic for Applications de:Visual Basic for Applications es:Visual Basic for Applications fr:Visual Basic for Applications ko:VBA hr:Visual Basic for Applications id:Visual Basic for Applicationsnl:Visual Basic for Applications ja:Visual Basic for Applicationspt:Visual Basic for Applicationssk:Visual Basic for Applications sv:Visual Basic for Applications th:Visual Basic for Applications tr:Visual Basic for Applications uk:Visual Basic for Applications vi:VBA zh:Visual Basic for Applications

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.