Microsoft visual basic для приложений windows

From Wikipedia, the free encyclopedia

From Wikipedia, the free encyclopedia

Visual Basic for Applications

Paradigm Multi-paradigm
Developer Microsoft
First appeared 1993; 30 years ago
Stable release

7.1 (Office 2021)

Typing discipline Static/Dynamic Hybrid, Strong/Weak Hybrid
OS Microsoft Windows, macOS
License Commercial proprietary software
Influenced by
QuickBASIC, Visual Basic

Visual Basic for Applications (VBA) is an implementation of Microsoft’s event-driven programming language Visual Basic 6.0 built into most desktop Microsoft Office applications. Although based on pre-.NET Visual Basic, which is no longer supported or updated by Microsoft, the VBA implementation in Office continues to be updated to support new Office features.[1][2] VBA is used for professional and end-user development due to its perceived ease-of-use, Office’s vast installed userbase, and extensive legacy in business.

Visual Basic for Applications enables building user-defined functions (UDFs), automating processes and accessing Windows API and other low-level functionality through dynamic-link libraries (DLLs). It supersedes and expands on the abilities of earlier application-specific macro programming languages such as Word’s WordBASIC. It 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.

As its name suggests, VBA is closely related to Visual Basic and uses the Visual Basic Runtime Library. However, VBA code normally can only run within a host application, rather than as a standalone program. VBA can, however, control one application from another using OLE Automation. For example, VBA can automatically create a Microsoft Word report from Microsoft Excel data that Excel collects automatically from polled sensors. VBA can use, but not create, ActiveX/COM DLLs, and later versions add support for class modules.

VBA is built into most Microsoft Office applications, including Office for Mac OS X (except version 2008), and other Microsoft applications, including Microsoft MapPoint and Microsoft Visio. VBA is also implemented, at least partially, in applications published by companies other than Microsoft, including ArcGIS, AutoCAD, CorelDraw, Kingsoft Office, LibreOffice,[3] Reflection,[4] SolidWorks,[5] WordPerfect, and UNICOM System Architect (which supports VBA 7.1).

Design[edit]

Code written in VBA is compiled[6] to Microsoft P-Code (pseudo-code), a proprietary intermediate language, which the host applications (Access, Excel, Word, Outlook, and PowerPoint) store as a separate stream in COM Structured Storage files (e.g., .doc or .xls) independent of the document streams. The intermediate code is then executed[6] by a virtual machine (hosted by the host application). Despite its resemblance to many old BASIC dialects (particularly Microsoft BASIC, from which it is indirectly derived), VBA is incompatible with any of them except 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 incompatible with Visual Basic .NET (VB.NET). VBA is proprietary to Microsoft and, apart from the COM interface, is not an open standard.

Automation[edit]

Interaction with the host application uses OLE Automation. Typically, the host application provides a type library and application programming interface (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.

Visual Basic for Applications 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. This is achieved through what is referred to as Early or Late Binding. 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.

As an example, VBA code written in Microsoft Access can establish references to the Excel, Word and Outlook libraries; this allows creating an application that – for instance – runs a query in Access, exports the results to Excel and analyzes them, and then formats the output as tables in a Word document or sends them as an Outlook email.

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 provides a user interface in the form of UserForms, which can host ActiveX controls for added functionality.

Inter-process communication automation includes the Dynamic Data Exchange (DDE) and RealTimeData (RTD) which allows calling a Component Object Model (COM) automation server for dynamic or realtime financial or scientific data.[7]

Security concerns[edit]

As with any common programming language, VBA macros can be created with 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. End-users can protect themselves from attack by disabling macros from running in an application or by granting permission for a document to run VBA code only if they are sure that the source of the document can be trusted.

In February 2022, Microsoft announced its plan to block VBA macros in files downloaded from the Internet by default in a variety of Office apps due to their widespread use to spread malware.[8]

Version history[edit]

  • VBA was first launched with MS Excel 5.0 in 1993. It became an instant success among developers to create corporate solutions using Excel. Inclusion of VBA with Microsoft Project, Access and Word replacing AccessBASIC and WordBASIC respectively made it more popular.
  • VBA 4.0 is the next famous release with a totally upgraded version compared to previous one. Released in 1996, it is written in C++ and became an object oriented language.
  • VBA 5.0 was launched in 1997 along with all of MS Office 97 products. The only exception for this was Outlook 97 which used VBScript.
  • VBA 6.0 and VBA 6.1 were launched in 1999, notably with support for COM add-ins in Office 2000. VBA 6.2 was released alongside Office 2000 SR-1.
  • VBA 6.3 was released after Office XP, VBA 6.4 followed Office 2003 and VBA 6.5 was released with Office 2007.
  • Office 2010 includes VBA 7.0. There are no new features in VBA 7 for developers compared to VBA 6.5 except for 64-bit support. However, after VBA 6.5/Office 2007, Microsoft stopped licensing VBA for other applications.
  • Office 2013, Office 2016, Office 2019 and Office 2021 include VBA 7.1.

Development[edit]

As of July 1, 2007, Microsoft no longer offers VBA distribution licenses to new customers. Microsoft intended to add .NET-based languages to the current version of VBA ever since the release of the .NET Framework,[9] of which versions 1.0 and 1.1 included a scripting runtime technology named Script for the .NET Framework.[10] Visual Studio .NET 2002 and 2003 SDK contained a separate scripting IDE called Visual Studio for Applications (VSA) that supported VB.NET.[11][12][13] One of its significant features was that the interfaces to the technology were available via Active Scripting (VBScript and JScript), allowing even .NET-unaware applications to be scripted via .NET languages. However, VSA was deprecated in version 2.0 of the .NET Framework,[13] 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).

Microsoft dropped VBA support for Microsoft Office 2008 for Mac.[14][15] VBA was restored in Microsoft Office for Mac 2011. Microsoft said that it has no plan to remove VBA from the Windows version of Office.[16][17]

With Office 2010, Microsoft introduced VBA7, which contains a true pointer data type: LongPtr. This allows referencing 64-bit address space. The 64-bit install of Office 2010 does not support common controls of MSComCtl (TabStrip, Toolbar, StatusBar, ProgressBar, TreeView, ListViews, ImageList, Slider, ImageComboBox) or MSComCt2 (Animation, UpDown, MonthView, DateTimePicker, FlatScrollBar), so legacy 32-bit code ported to 64-bit VBA code that depends on these common controls will not function. This did not affect the 32-bit version Office 2010.[18] Microsoft eventually released a 64-bit version of MSComCtl with the July 27th, 2017 update to Office 2016.[19]

See also[edit]

  • Visual Studio Tools for Applications
  • Visual Studio Tools for Office
  • Microsoft Visual Studio
  • Microsoft FrontPage
  • OpenOffice Basic
  • LotusScript
  • Microsoft Power Fx

References[edit]

  1. ^ «Compatibility Between the 32-bit and 64-bit Versions of Office 2010». msdn.microsoft.com.
  2. ^ o365devx. «What’s new for VBA in Office 2019». docs.microsoft.com. Retrieved 2022-05-02.
  3. ^ «Support for VBA Macros». The Document Foundation — LibreOffice. Retrieved 3 January 2023.
  4. ^ «Reflection Desktop VBA Guide». docs.attachmate.com. Retrieved 2017-07-01.
  5. ^ «2016 SolidWorks Help – VBA». help.solidworks.com. Retrieved 2016-07-25.
  6. ^ a b «ACC: Visual/Access Basic Is Both a Compiler and an Interpreter». Microsoft. 2012. Archived from the original on 2012-10-21.
  7. ^ «How to set up and use the RTD function in Excel». msdn.microsoft.com.
  8. ^ «Microsoft to Block Office VBA Macros by Default». The Verge. Retrieved 2022-09-26.
  9. ^ «Visual Studio for Applications». Archived from the original on 2007-12-17.
  10. ^ «Introducing Visual Studio for Applications». msdn.microsoft.com.
  11. ^ «Script Happens .NET». msdn.microsoft.com.
  12. ^ «Microsoft Takes Wraps Off VSA Development Technology». Archived from the original on 2007-12-17.
  13. ^ a b «VSA scripting in .NET». Archived from the original on 2007-02-11.
  14. ^ «WWDC: Microsoft updates Universal status of Mac apps». Macworld. 2006-08-07. Retrieved 2007-05-25.
  15. ^ «What is Microsoft Office and Office 365 – FAQs».
  16. ^ «The Reports of VBA’s Demise Have Been Greatly Exaggerated».
  17. ^ «Clarification on VBA Support». Archived from the original on 2008-01-19.
  18. ^ «Compatibility Between the 32-bit and 64-bit Versions of Office 2010». msdn.microsoft.com.
  19. ^ «Release notes for Monthly Channel releases in 2017». learn.microsoft.com. Retrieved 2022-11-13.

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

Main article: OLE 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

Use of named column variables x & y in Microsoft Excel; y = x*x is calculated using the formula displayed in the formula box, which is copied down the entire y-column.

File:Functions in Excel.PNG

Use of a user-defined function sq(x) of named variable x in Microsoft Excel. Function supplied automatically from the code in the Visual Basic for Applications editor.

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

Subroutine in Excel calculates the square of named column variable x read from the spreadsheet, and writes it into the named column variable y.

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)

Main article: Visual Studio Tools for Applications

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

  • Microsoft Visual Basic
  • Visual Studio Tools for Office
  • Visual Studio Tools for Applications
  • Microsoft Visual Studio
  • Microsoft Visual Basic.NET
  • Microsoft Excel
  • Microsoft Word
  • Microsoft FrontPage
  • Microsoft Access
  • Microsoft PowerPoint

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.

  4. Steven Roman (1999). Writing Word Macros. Sebastopol CA: O’Reilly. Chapter 10. ISBN 1565927257.

  5. Matthew MacDonald (2005). Excel: The Missing Manual. Sebastopol CA: O’Reilly. pp. 655. ISBN 0596006640.

  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.
  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. 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». Retrieved 2010-04-21.
  17. «Microsoft to bring back Visual Basic in Office for Mac». 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

  • Excel and VB.Net
  • MS Access VBA Examples
  • A VBA Primer

Microsoft Office

History • Website • Microsoft Product Activation • Genuine Advantage
Windows
3.0 • 95 • 97 • 2000 • XP • 2003 • 2007 • 2010 • 2013 • 2016 • 2019 • 2021
Mac OS/OS X/macOS
3.0 • 4.2 • 98 • 2001 • X • 2004 • 2011 • 2016 • 2019 • 2021
Applications (List)
Desktop
Access • Excel (Viewer) • InfoPath • Lync • OneNote • Outlook (Hotmail Connector • Add-ins) • PowerPoint (Viewer) • Project • Publisher • SharePoint (Designer • Workspace) • Visio • Word (Viewer)
Server
Forms ServerGroove Server • Lync Server • PerformancePoint ServerProject ServerProject Portfolio ServerSharePoint Server • Excel Services • InfoPath Forms Services
Mobile
Office Mobile
Online
Live MeetingOffice LiveOffice Web AppsOutlook Web App • Office 365 • Outlook.com
Office tools
Microsoft Office shared toolsRibbon HeroRibbon Hero 2
Discontinued
AccountingDocument Imaging • Entourage • FrontPage • Microsoft InterConnectLiquid MotionMail • Office Assistants • Microsoft PhotoDraw • Photo Editor • Schedule+ • Snapshot Viewer for AccessMicrosoft Vizact
Related products
Works • MapPoint • Search ServerLanguage Packs
Technologies
Information Bridge Framework • Object Linking and Embedding • Office Open XML • Office XML formatsSmart tagsVisual Basic for Applications
  1. REDIRECT Template:Microsoft development tools

af:VBA
ar:فيجوال بيسك للتطبيقات
bs:Microsoft VBA
bg:Visual Basic for Applications
da:Visual Basic for Applications
ko:VBA
hr:Visual Basic for Applications
nl:Visual Basic for Applications
ja:Visual Basic for Applications
pt:Visual Basic for Applications
sk:Visual Basic for Applications
sv:Visual Basic for Applications
th:Visual Basic for Applications
tr:Visual Basic for Applications

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

Main article: OLE 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

Use of named column variables x & y in Microsoft Excel; y = x*x is calculated using the formula displayed in the formula box, which is copied down the entire y-column.

File:Functions in Excel.PNG

Use of a user-defined function sq(x) of named variable x in Microsoft Excel. Function supplied automatically from the code in the Visual Basic for Applications editor.

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

Subroutine in Excel calculates the square of named column variable x read from the spreadsheet, and writes it into the named column variable y.

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)

Main article: Visual Studio Tools for Applications

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

  • Microsoft Visual Basic
  • Visual Studio Tools for Office
  • Visual Studio Tools for Applications
  • Microsoft Visual Studio
  • Microsoft Visual Basic.NET
  • Microsoft Excel
  • Microsoft Word
  • Microsoft FrontPage
  • Microsoft Access
  • Microsoft PowerPoint

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.

  4. Steven Roman (1999). Writing Word Macros. Sebastopol CA: O’Reilly. Chapter 10. ISBN 1565927257.

  5. Matthew MacDonald (2005). Excel: The Missing Manual. Sebastopol CA: O’Reilly. pp. 655. ISBN 0596006640.

  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.
  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. 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». Retrieved 2010-04-21.
  17. «Microsoft to bring back Visual Basic in Office for Mac». 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

  • Excel and VB.Net
  • MS Access VBA Examples
  • A VBA Primer

Microsoft Office

History • Website • Microsoft Product Activation • Genuine Advantage
Windows
3.0 • 95 • 97 • 2000 • XP • 2003 • 2007 • 2010 • 2013 • 2016 • 2019 • 2021
Mac OS/OS X/macOS
3.0 • 4.2 • 98 • 2001 • X • 2004 • 2011 • 2016 • 2019 • 2021
Applications (List)
Desktop
Access • Excel (Viewer) • InfoPath • Lync • OneNote • Outlook (Hotmail Connector • Add-ins) • PowerPoint (Viewer) • Project • Publisher • SharePoint (Designer • Workspace) • Visio • Word (Viewer)
Server
Forms ServerGroove Server • Lync Server • PerformancePoint ServerProject ServerProject Portfolio ServerSharePoint Server • Excel Services • InfoPath Forms Services
Mobile
Office Mobile
Online
Live MeetingOffice LiveOffice Web AppsOutlook Web App • Office 365 • Outlook.com
Office tools
Microsoft Office shared toolsRibbon HeroRibbon Hero 2
Discontinued
AccountingDocument Imaging • Entourage • FrontPage • Microsoft InterConnectLiquid MotionMail • Office Assistants • Microsoft PhotoDraw • Photo Editor • Schedule+ • Snapshot Viewer for AccessMicrosoft Vizact
Related products
Works • MapPoint • Search ServerLanguage Packs
Technologies
Information Bridge Framework • Object Linking and Embedding • Office Open XML • Office XML formatsSmart tagsVisual Basic for Applications
  1. REDIRECT Template:Microsoft development tools

af:VBA
ar:فيجوال بيسك للتطبيقات
bs:Microsoft VBA
bg:Visual Basic for Applications
da:Visual Basic for Applications
ko:VBA
hr:Visual Basic for Applications
nl:Visual Basic for Applications
ja:Visual Basic for Applications
pt:Visual Basic for Applications
sk:Visual Basic for Applications
sv:Visual Basic for Applications
th:Visual Basic for Applications
tr:Visual Basic for Applications

Языки программирования насчитывают несколько десятков вариантов. Какие-то из них подходят для нативной разработки, а какие-то – для кроссплатформенной. Visual Basic – язык программирования, который произошел от более старого языка – Basic.

В данной статье предстоит разобраться с особенностями составления Бейсик программ. Ориентироваться будем на VB, так как он встречается на практике чаще. А еще необходимо выяснить особенности выбранного ЯП и сферы его применения. Эта информация поможет понять, стоит ли вообще начинать изучение Visual Basic (далее он будет называться просто «Бейсик»).

VB – это…

Строки кода для работоспособного программного обеспечения удастся написать на любом выбранном языке. «Бейсик» — полноценный ЯП, а также специальная интегрированная среда разработки. Она была создана корпорацией Microsoft. Это – наследник BASIC с огромным количеством диалектов.

VB предусматривает:

  • процедурное программирование;
  • написание кода при помощи объектно-ориентированных принципов;
  • компонентно-ориентированность.

Соответствующая интегрированная среда предлагает разработчику множество инструментов разработки с упором на визуальную составляющую. Это способствует быстрому проектированию уникальных пользовательских интерфейсов. Огромный код прописывать не придется – достаточно добавить несколько элементов в рабочую область, а затем написать пару строк.

История развития

Сам BASIC появился в 1964 году. В 80-х он стал утрачивать свою актуальность ввиду сложности. Исходный код даже самого элементарного приложения по сравнению с «конкурентами» содержал множество строчек и не выделялся быстродействием.

Все это привело к тому, что разработчики начали задумываться над созданием диалектов BASIC. А компания Microsoft выпустила QBasic, а чуть позже – VB.

Популярность этот язык программирования получил, начиная с версии 3.0, которая позволила взаимодействовать с базами данных. Освоить такой «Бейсик» мог даже рядовой пользователь, далекий от вопросов разработки. Элементарное приложение можно было составить в несколько строк, половина из которых прописывалась автоматически во время использования встроенных инструментов.

Традиционный VB появился в 1998 году – это его последняя версия. Далее, после сборки 6.0, Майкрософт решили разделить язык на несколько векторов. Они стали развиваться VB на платформе .Net, а также адаптированные версии для решения задач локального характера.

Виды VB

Рассматривая Basic типа Visual, нужно понимать – у него существуют разновидности. В зависимости от выбранного варианта программист будет решать те или иные задачи. Поэтому перед непосредственным написанием Бейсик программы, нужно определиться, чем именно пользоваться.

Классика

Basic Classic – классический VB. Он ориентирован на разработку приложений под Windows. Используется преимущественно как инструмент написания строк кода для соответствующей операционной системы. Предусматривает широкий спектр возможностей и инструментов, ориентированных на программирование под Windows.

Сюда относят:

  • просмотр переменных и структур практически моментально;
  • встроенный отладчик;
  • отдельное удобное окно отладки;
  • всплывающие подсказки.

Classic не пишется в отличных от изначальной средах разработки.

VBA

Аналог предыдущего варианта, но направленный на то, чтобы пользователь мог создать макросы и прикладные утилиты для уже имеющихся приложений. Получил достаточно широкое распространение. Такой результат получен за счет совместимости с MS Office.

VBA позволяет написать несколько строк для автоматического выполнения различных задач. Используется даже в 2022 году, но из-за отсутствия достаточно контроля безопасности применение чужих макросов может быть опасно. Это связано с образованием макровирусов.

VBScript

Урезанный вариант Classic. Такой Basic является скриптовым. Он подходит для администрирования на базе Windows. Активно применяется для создания страниц ASP и всевозможных сценариев под IE.

Basic .NET

Вариант, появившийся после версии 6.0 классического VB. Совершенно новый вектор развития от Microsoft. Ориентирован на работу с платформой .NET. Он:

  • использует в работе библиотеку классов из .НЕТ;
  • имеет объектно-ориентированную парадигму;
  • обладает полиморфизмом и строгой типизацией.

Позволяет создавать крупномасштабные проекты с минимальным количеством строк исходного кода. Полученные на выходе утилиты отличаются скоростью работы, но они все равно уступают софту, составленному на C++ или C#.

Особенности

Перед тем, как делать контент на VB, нужно изучить особенности и основы языка. Рассматриваемый вариант позволяет задействовать при разработке множество визуальных компонентов и контролов, определять атрибуты и действия для элементов, создавать дополнительные строки для расширения стандартного функционала.

Составить элементарную утилиту сможет даже новичок, далекий от принципов разработки. Создание форм осуществляется через drag and drop, который отнимает минимум времени. Достаточно перетащить компонент на экран, а затем присвоить ему строки с теми или иными командами.

Компилятор VB включает в себя другие языки программирования Visual Studio, но ограничения в интегрированной среде не позволяют писать определенные разновидности контента. Также к особенностям ЯП относят:

  1. Объединение операторов. Принцип работает относительно логических и битовых вариантов.
  2. Автоматическое конвертирование целочисленных значений в вещественные. Это происходит после деления.
  3. Объявление массивов при помощи обозначения границ: верхних и нижних. Аналогичные принципы предусматривает Fortran и Pascal.
  4. Объединение VB с COM. Сюда также относится Windows.
  5. Наличие специального типа данных — variant. Он используется для переменных, в которых не указан тип данных.

Язык поддерживает статическую и динамическую строгую типизацию. Является компилируемым и интерпретируемым. За счет совместимости с Windows даже новичок сможет создавать программы с расширением .exe.

Преимущества и недостатки

Рассматриваемый «способ» создания программ – это интересный вариант для новичков. Минимум строк – максимум функциональности с упором на визуальные компоненты. Он обладает простым синтаксисом, с которым сможет справиться новичок. Является неплохим вариантом для тех, кто хочет попробовать собственные силы в разработке.

К преимуществам «Бейсика» относят:

  1. Быстрое написание контента, ориентированного на операционные системы Windows.
  2. Наличие защиты от ошибок. Она помогает делать программы стабильными. Этот момент до сих пор часто критикуют.
  3. Возможность применения WnAPI для расширения итогового функционала программ.
  4. Выбор типа компиляции. Строки программы можно скомпоновать в машинный код или P-код в несколько кликов.

А еще при написании программ предстоит работать с достаточно красивым и понятным интерфейсом редактора. В нем невозможно запутаться.

Недостатки тоже есть:

  1. Ориентированность преимущественно на Mac OS X и Windows. Другие системы не поддерживаются.
  2. Скорость работы. Если сравнивать программы на «Бейсике с визуализацией», то они будут уступать софту, написанному на других языках с ООП.
  3. Отсутствие механизмов наследования реализации имеющихся компонентов. Поддерживается лишь наследование интерфейсов. 

Для того, чтобы строки написанной программы работали на устройстве, потребуется установить на компьютер отдельную библиотеку. А именно – msvbvm.dll.

Основы языка

Можно найти разнообразные уроки и туториалы, которые расскажут об особенностях написания программ на VB. Но перед тем, как создавать собственные утилиты, стоит обратить внимание на основы разработки. Далее представлены ключевые знания, которые помогут продвинуться в выбранном направлении с нуля.

Комментарии

«Бейсик» поддерживает возможность вставки комментариев. Для этого можно использовать или новую строку, или уже имеющуюся. Во втором случае комментарий вставляется после основного кода.

Если разработчику необходимо провести проверку той или иной процедуры, он может просто превратить ее в упомянутый компонент. Для этого в самом начале строки ставится знак «апостроф». VBA будет игнорировать инструкцию при обработке кода.

Типы данных

Для того, чтобы задать тип данных, нужно использовать оператор Dim, после которого в строке приложения указывается имя. Далее следует ключевое слово As с типом переменной, в противном случае можно обойтись записью Dim имя_переменной. Соответствующий элемент получит тип variant.

Язык поддерживает автоматическое создание типов переменных. Для этого не нужно указывать в строках кода конструкцию Option Explicit в разделе деклараций. Подобный прием иногда приводит к снижению скорости работы полученного исходного контента.

В VB 6.0 поддерживаются следующие типы данных:

  1. Byte. Нужен для хранения чисел в диапазоне от 0 до 255.
  2. Integer. Целое. Обозначается суффиксом %. Хранит целочисленные от -32 768 до 2 767.
  3. Long. Обозначается в строке как &. Это – «длинное целое».
  4. Single (!). Позволяет задавать переменные с точкой одинарной точности.
  5. Double (#). Числа с плавающей точкой двойной точности.
  6. Decimal (CDec). Масштабируемое целое. Используется для того, чтобы применять десятичное представление чисел в строках.
  7. Boolean. Булевый тип. Хранит только «истину» и «ложь». Используется при работе с логическими операторами.
  8. String ($). Это – строка переменной длины. Помогает хранить строковые и символьные данные.
  9. String*N. Строка постоянной длины.
  10. Date. Тип данных, ориентированный на работу с датой и временем в программе.
  11. Object (Set). Помогает хранить ссылки на объект.
  12. Currency (@). Денежный тип. Имеет до 4 цифр после запятой и до 14 – перед ней.

Также здесь есть тип Variant. Он содержит данные любого характера, включая ссылки на объекты и пользовательские массивы. Будет присваиваться в строке кода, если разработчик не установил самостоятельно тип данных для той или иной переменной.

Операторы

Операторы для написания собственного программного обеспечения используются разные. Есть «стандартные» варианты, которые известны большинству ЯП, а есть операторы для конкатенации.

В данную категорию можно отнести:

  1. Присваивание (=). Помогает присваивать переменным те или иные значения. Может быть задан при помощи ключевого слова Let. Set используется для присвоения переменной объектного типа. ЯП поддерживает многократное присваивание.
  2. Сложение (+).
  3. Умножение (*).
  4. Деление (/).
  5. Вычитание (-).
  6. Степень (^).
  7. Целочисленное деление (). Первое число будет поделено на второе с отбрасыванием дробной части. Округление не производится.
  8. Деление по модулю (Mod). В ходе операции первое число делится на второе. Происходит возврат только остатка от выполненного действия.
  9. Равенство (=).
  10. Больше, чем. Сюда также относят «меньше, чем» (> и <).
  11. Больше или равно и меньше или равно (>= и <=).
  12. Не равно (<>).
  13. Сравнение объектов (Is). Будет определять, ссылаются ли переменные объектного типа на один и тот же элемент или на разные.
  14. Подобие (Like). При применении происходит сравнение строкового объекта с шаблоном. Далее система сообщает, подходит ли этот компонент.
  15. Логическое И (And), ИЛИ (or), отрицание (Not), исключение (Xor).
  16. Эквивалентность (Eqv). Производит оценку эквивалентности двух выражение. Если принцип соблюден, система вернет True.
  17. Импликация (Imp). False возвращается системой, если E1 = True, а E2 = False. В противном случае значение окажется True.

Также есть операторы конкатенации. + применяется для того, чтобы проводить операцию со строками. Когда обе части выражения – это символьный тип данных, операция «соединения» проходит успешно. Если одна – это число, а другая не может быть преобразована в соответствующий вариант, появляется ошибка.

Оператор & помогает автоматически преобразовывать выражения и значения в строковый тип. После этого «склеивание» будет производиться без проблем.

О модулях и классах

Бейсик программы хранят исходные коды в виде модулей. Они бывают разного вида:

  1. Формы. Обладают расширением .frm. Выступает такой модуль «базовым» для большинства программ. Содержит процедуры обработки события, общие процедуры, переменные, константы и их виды, внешние операции. При раскрытии формы в обычном текстовом редакторе появляется описание, элементы управления и свойства.
  2. Стандартный. Расширение — .bas. Это – контейнер для операций, функций и объявлений, к которым чаще всего получают доступ другие модули программы. Содержат глобальные и иные переменные, а также соответствующие процедуры. Код, написанный внутри, может не иметь связи с конкретной программой.
  3. Класса (.cls). Это – основа объектно-ориентированной разработки. Позволяет создавать новые объекты. Полученные компоненты могут обладать собственными свойствами, методами, а также событиями.

Этого достаточно, чтобы программировать софт на VB, если пользователь уже имел опыт в разработке. Всевозможные уроки и туториалы помогут быстро создать собственную программу, хоть и элементарную.

Простая консольная программа

После изучения базовых возможностей и функций можно приступить к созданию собственной первой утилиты. Это не слишком сложно, особенно если придерживаться определенного алгоритма действий.

Начать операцию необходимо с предварительной подготовки. В нее включено изучение основ VB, а также установка соответствующей интегрированной среды. Далее каждый этап будет рассмотрен более подробно.

Начало проекта

Первый шаг – создание нового проекта. В шаблоне по умолчанию есть все, что только может потребоваться для запуска итогового контента. Чтобы сделать проект на выбранном языке, необходимо:

  1. Запустить Visual Studio.
  2. Кликнуть по кнопке «Создать проект». Это делается в правой части открытого софта.
  3. Выбрать интересующий ЯП.
  4. Определиться с типом операционной системы. Пример – Windows. Далее предстоит указать вид проекта – «Консоль».
  5. Щелкнуть по надписи «Консольное приложение», а затем нажать на «Далее».
  6. Ввести имя проекта. Пример – WhatIsYourName.
  7. Выбрать в долгосрочной поддержке .Net 6.0. Обычно это происходит автоматически. Если нет – кликнуть по подходящему варианту вручную.

Как только все готово, можно нажать на «Создать». Через несколько секунд пользователь увидит на экране готовую форму. Остальные действия предстоит выполнять в ее пределах.

Запуск

После выбора подходящего шаблона и установки имени для него произойдет создание файла Program.vb. Имеющийся код изначально осуществляет вызов метода WriteLine. Он позволяет отобразить литеральную строчку «Привет, Мир!» в консольном окошке.

Выполнить соответствующую запись можно при помощи нескольких подходов – в режиме отладки, а также в качестве обычного автономного программного обеспечения на задействованном устройстве.

Запуск в отладке

Для этого необходимо:

  1. Нажать на кнопку WhatIsYourName в среде. Можно просто кликнуть по клавише F5.
  2. На экране появится консоль с соответствующей надписью. Это – режим отладки.
  3. Чтобы закрыть окно и вернуть в «прежнее состояние», потребуется нажать на любую клавишу.

Данный подход хорош для непосредственной проверки готовой утилиты или ее частей.

Автономный режим

А этот метод позволяет запускать программное обеспечение за пределами «Студии». Для этого потребуется сформировать самостоятельный контент с исполняемым файлом:

  1. Перейти в меню «Сборка».
  2. Кликнуть по надписи «Собрать решение».
  3. Выбрать ПКМ WhatIsYourName, а затем «Открыть в проводнике».
  4. Перейти к каталогу binDebugnet5.0.
  5. Запустить WhatIsYourName.exe.

Метод Main завершится после того, как произойдет выполнение одной инструкции. Окно консоли сразу же закроется. Но эту проблему удается решить. Рекомендация дана ниже.

Код для указания запроса

Теперь можно добавить фрагмент утилиты, которая запросит пользовательское имя. После обработки – выведет его на экран вместе с текущим временем и датой. А еще необходимо прописать команду, которая не позволит окну консоли закрываться до нажатия нужной кнопки:

  1. Ввести код после Sub Main и перед End Sub. В ходе операции требуется заменить WriteLine.
  2. Нажать на кнопку WhatIsYourName или на F5 на клавиатуре. Это поможет собрать утилиту.
  3. Ввести запрошенные данные. В рассматриваемой ситуации – имя.
  4. Щелкнуть по любой кнопке на клавиатуре.

После описанных действий меню отладки будет закрыто. Можно собрать исполняемый файл и посмотреть, что получилось.

Система управления с GIT

GIT – система управления контроля версий. Является одной из самых популярных. Можно связать получившийся контент с Git. У VStudio имеются встроенные инструменты для проведения операции.

Чтобы связать с системой контроля версий исходную утилиту, нужно:

  1. В строчке состояния в правом нижнем углу «Студии» щелкнуть по «Добавить в систему управления версиями».
  2. Щелкнуть по GIT.
  3. Войти в GitHub. Это потребуется проделать в окне «Создать репозиторий…». Имя будет присвоено автоматически. Репозиторий по умолчанию является частным.
  4. Нажать на кнопку «Создать и отправить».

В строчке состояния появится новая информация. Первый значок со стрелочками указывает на входящие и исходящие фиксации в текущей ветке. Его используют для получения соответствующих компонентов. Можно отобразить фиксации в первую очередь, нажав на значок, а после – по «Посмотреть входящие/исходящие…».

Второй знак (с карандашиком) демонстрирует незафиксированные корректировки. Если по нему нажать, соответствующие данные отобразятся в Git Changes.

Очистка

Когда работа с проектом завершена, утилита сформирована, а программист больше не планирует им пользоваться, нужно провести очистку ресурсов:

Перейти в «Обозреватель решений».

  1. ПКМ нажать по интересующему проекту. Откроется его контекстное меню. В нем нужно выбрать «Открыть в проводнике».
  2. Закрыть «Студию».
  3. Перейти на два уровня папок вверх. Делается это непосредственно в «Проводнике».
  4. Нажать ПКМ по имени имеющегося проекта и скомандовать «Удалить».

Basic программа стерта с устройства. Теперь можно начать полноценную разработку нового софта.

Интересные примеры

Далее будут приведены довольно интересные примеры контента на рассмотренном ЯП. Это – готовые решения для выполнения тех или иных задач:

  1. Форма входа с подтверждением. Не совсем полноценное приложение. Больше отражает функцию. В меню проекта нужно разметить на экране кнопку, а ей присвоить следующую запись:
  2. Пароль для запуска ПО. Полезная возможность, особенно если хочется обеспечить дополнительную защиту или скрыть приложение от посторонних глаз. Запись осуществляется в стандартном проекте: . Здесь «12345» — это пароль. Его можно задать по собственному усмотрению.
  3. Вывод сообщения. Элементарная возможность:
  4. Рисование. Это – своеобразный графический мини-редактор. Рисовать клиент сможет прямо в открывающейся форме. В стандартном проекте предстоит указать следующее:.Цвета меняются при помощи значения QBColor(0), где 0 – это любая другая желаемая цифра.
  5. Запуск только один раз. Если попытаться активировать соответствующий контент повторно, система выдаст специальное сообщение: .
  6. Перезагрузка устройства. Рекомендуется размещать запись «на кнопке»: .

А еще можно посмотреть, сколько работает устройство. Основан предложенный пример на библиотеке kernel32. За счет этого сначала необходимо подключить DLL-библиотеку:

Все это – элементарные возможности и функции, которые помогут дополнить практически любое программное обеспечение.

Изучение с нуля

Программы на Бейсике составлять не слишком сложно. Чтобы обучиться основам разработки на нем, можно смотреть разнообразные уроки. А еще можно поискать сопутствующую литературу по интересующему ЯП.

Чтобы быстрее добиться успеха «с нуля», рекомендуется обратить внимание на дистанционные онлайн курсы. Пример – от образовательного центра OTUS. Там есть программы, благодаря которым в сжатые сроки можно освоить любую инновационную IT-профессию.

Пользователи смогут выбрать один или несколько курсов. Они длятся до 12 месяцев. В процессе клиентам обеспечено постоянное кураторство и все необходимые для погружения в тему материалы, поданные понятным языком. Море практики, интересных заданий, а также помощь в формировании портфолио.

По окончании дистанционных курсов пользователи получают специальные онлайн сертификаты. Это – документальное официальное подтверждение имеющегося багажа знаний и умений.

Хотите освоить современную IT-специальность? Огромный выбор курсов по востребованным IT-направлениям есть в Otus!

Некоторые приложения пакета Microsoft Office, такие как Word, Excel, Access, Outlook, позволяют использовать для решения пользовательских задач язык программирования Visual Basic for Applications (VBA).

Для того чтобы использовать возможности VBA, макросы, процедуры и надстройки, написанные на этом языке программирования, необходимо чтобы компонент Visual Basic для приложений был установлен вместе с приложениями пакета Microsoft Office.

Как проверить установлен ли Visual Basic для приложений?

Самый простой способ проверить наличие либо отсутствие установленного VBA это попробовать его запустить. Запустить VBA можно сочетанием клавиш Alt+F11 на клавиатуре, либо кнопкой «Visual Basic» на вкладке «Разработчик». По умолчанию вкладка «Разработчик» отключена во всех приложениях пакета Microsoft Office, поэтому предварительно ее нужно отобразить в настройках ленты.

Итак, если VBA установлен, то нажатие горячих клавиш либо кнопки «Visual Basic» на ленте приложения приводит к появлению окна редактора Visual Basic на экране монитора. Выглядит редактор примерно так, как показано на изображении ниже.

redaktor VBA v excel

В случае, если окно редактора не появилось, то компонент Visual Basic для приложений необходимо установить.

Как установить Visual Basic для приложений?

Чтобы установить компонент пакета Visual Basic for Applications, необходимо нажать кнопку Пуск, зайти в Панель управления/Программы и компоненты, выбрать программу Microsoft Office и нажать кнопку «Изменить», либо запустить установочный файл Setup.exe.

izmenit ustanovki programmy

Далее выбрать опцию «Добавить или удалить компоненты»,  в параметрах установки выбрать компонент Visual Basic для приложений и доустановить его.

как установить компонент VBA

Другие материалы по теме:

Понравилась статья? Поделить с друзьями:
  • Microsoft visual basic for applications скачать для windows 10 64
  • Microsoft visio для windows 10 купить
  • Microsoft visio для windows 10 крякнутый
  • Microsoft visio для windows 10 torrent x64
  • Microsoft visio для windows 10 64 bit скачать бесплатно торрент