This Excel tutorial explains the VBA environment in Excel 2003 (with screenshots and step-by-step instructions).
What is VBA?
The Microsoft Visual Basic window displays your VBA environment in Excel 2003:
VBA standards for Visual Basic for Applications and is the language embedded within your spreadsheet in Excel 2003.
You use VBA in Excel whenever you do one of the following:
- Record a macro.
- Run a macro.
- Create a new function.
- Create a new subroutine.
- Define a variable.
- Place code on the click of a button.
These are just some of the examples of when you might be running VBA code in Excel 2003.
Содержание
- Excel VBA
- Contents
- Service Pack [ edit | edit source ]
- Macro Security [ edit | edit source ]
- Macro Recording [ edit | edit source ]
- Enabling Developer tab [ edit | edit source ]
- Making an XLA [ edit | edit source ]
- Accessing the Registry [ edit | edit source ]
- Prevent Confirmation Popups In Excel [ edit | edit source ]
- Making Cells Read-Only [ edit | edit source ]
- Finding Non-Empty Portion of Worksheet [ edit | edit source ]
- Using Events [ edit | edit source ]
- Caveat: Uncaught Exceptions [ edit | edit source ]
- Caveat: Online-Help Typos [ edit | edit source ]
- Iterating Over MultiSelected Cells [ edit | edit source ]
- Exporting VBA Code [ edit | edit source ]
- Resize a Named Range [ edit | edit source ]
- Creating a Named Range [ edit | edit source ]
- Reading a File [ edit | edit source ]
- Writing to a File [ edit | edit source ]
- File Existence [ edit | edit source ]
- Directories [ edit | edit source ]
- Grep [ edit | edit source ]
- Clipboard [ edit | edit source ]
- Range [ edit | edit source ]
- Worksheet [ edit | edit source ]
- Searching [ edit | edit source ]
- Cell Formatting [ edit | edit source ]
- Color [ edit | edit source ]
- Visibility [ edit | edit source ]
- Hyperlink [ edit | edit source ]
- Temporary file [ edit | edit source ]
- Command Output [ edit | edit source ]
- Dimensions [ edit | edit source ]
- Comment [ edit | edit source ]
- IsEmpty [ edit | edit source ]
- IsNull [ edit | edit source ]
- Add-Ins at Startup [ edit | edit source ]
- Chart direct from VBA array data [ edit | edit source ]
- Nuking Retained State [ edit | edit source ]
Excel VBA
Contents
Microsoft Excel is a deep program rich in features and functionality. One of the most powerful features of Excel is the ability to write programs in Visual Basic for Applications that run «behind» your worksheets to turn Excel into a calculation-oriented development platform for creating special purpose spreadsheets which can function as applications in their own right.
Service Pack [ edit | edit source ]
A service pack (in short SP) is a collection of updates, fixes or enhancements to a software program delivered in the form of a single installable package.
A service pack can be incremental, which means it only contains the updates that were not present in the previous service packs or, it can be cumulative, which means it includes the contents of all its predecessors. In the case of Microsoft’s products, an incremental update was called a service release. For example, Office 2000 must be upgraded to service release 1 (SR-1) before one can install SP2.
Macro Security [ edit | edit source ]
Macro security settings are located in the Trust Center. However, if you work in an organization, your system administrator might have changed the default settings to prevent anyone from changing any settings and execute macros.
Macro Recording [ edit | edit source ]
A great way of learning about Excel VBA is using its macro recording function. With the function, you tell Excel to start recording, then perform various steps as if you were working without a macro recorder, and finally, tell Excel to stop recording. VBA code corresponding to what you did using Excel GUI has been recorded by Excel. While the code often cannot be meaningfully used without a modification, by starting from it and modifying it you can save a lot of time that would otherwise be spent reading the VBA documentation.
- Excel 2000, 2003: Tools > Macro > Record New Macro.
- Excel 2007: View (tab) > Macros (group) > down-pointing triangle below Macros button > Record Macro
- Excel 2007: Developer (tab) > Code (group) > Record Macro
Enabling Developer tab [ edit | edit source ]
Developer tab allows you to insert various user interface controls such as buttons. In order to use it, you first have to enable it.
Menu paths to enable the tab:
- Excel 2007: round Office button > Excel Options (button at bottom) > Popular > Show Developer tab in the Ribbon (check box)
- Excel 2010: File (tab) > Options (button) > Customize Ribbon (button) > Developer (check box)
Making an XLA [ edit | edit source ]
An XLA is one way to make a VBA code-library. It’s basically just a normal spreadsheet(.xls file) but has its worksheets hidden. Here’s how to create a new one:
- New Workbook
- Save-As . Name it whatever
- Hit Alt-F11
- In the Project-tree, select VBAProject(whatever.xls)/ThisWorkbook
- Hit F4 to get Properties View
- Find Property IsAddin and set to True
- Hit Save
- Close Excel
- Rename whatever.xls to whatever.xla
Alternatively, you can use Save As / Excel AddIn.
Accessing the Registry [ edit | edit source ]
- Works on: Microsoft Excel 2002 SP-2
This recipe is for reading/writing keys local to your application—this is to provide persistent settings for your VBA app. It does not cover arbitrary access to the Registry (i.e. looking at any key).
The VBA sub/functions are SaveSetting and GetSetting . You can type the following into the Immediate window to get a feel for how these work:
If you want to iterate over all keys in a given section you can do so as follows:
You can also delete a registry key as follows:
FYI: Excel/VBA sticks this in the following registry location:
. where MyApplication and MyConfigSection are whatever you specified in your SaveSettings call.
They end up in HKEY_CURRENT_USERSoftwareVB and VBA Program SettingsMyApplicationNameMyConfigSection.
- Works on: Microsoft Excel 2002 SP-2
Make the following call from VBA:
Making Cells Read-Only [ edit | edit source ]
- Works on: Microsoft Excel 2002 SP-2
Finding Non-Empty Portion of Worksheet [ edit | edit source ]
A Worksheet has a maximum size of 65536 rows by 256 columns. However if you want to iterate over all cells you probably don’t want to visit all of the empty ones. For this purpose the Worksheet provides the UsedRange property. For example:
tells you how many non-empty rows are in the given worksheet. Empty rows which are in between the first and last used row are counted as well. Example: If a given Worksheet has entries in cells A7 and B16, used range is considered to be A7:B16, which counts for a total of 10 rows.
Using Events [ edit | edit source ]
- Works on: Microsoft Excel 2002 SP-2
Consider the following class definition—Assume its a class called CMyClass:
The main ideas here are:
- By declaring mySheet WithEvents, you’re saying that CMyClass is listening to mySheet’s events.
- By declaring the member sub mySheet_SelectionChange you’re indicating how an instance of CMyClass should react if mySheet experiences a selection change (i.e. the user selects a new cell or range of cells); The general pattern for events is sub memberVarName_EventName(params).
- You can disconnect the eventing between the given worksheet and CMyClass by setting mySheet = nothing;
- You can create classes that throw events of your design using:
- You would declare at the top of the class: Public Event SomeNiceEventName(YourFavoriteParam1 as WhateverType, etc. ),
- You could then raise that event (i.e. firing it to whatever listeners your class has) using RaiseEvent SomeNiceEvent(«Some nice event happened.»);
- VBA in Excel doesn’t like the letters r or c used as variables. Those letters mean ‘row’ and ‘column’ elsewhere.
A little more detail is given here: [1]
Caveat: Uncaught Exceptions [ edit | edit source ]
Caveat: Uncaught exceptions in event-handlers cause VBE to mysteriously reset. If you are causing an uncaught exception in an event-handler, you probably won’t get an error popup. Instead, VBE will just reset. For this reason you should make sure you’re catching exceptions in all of your event handlers.
Caveat: Online-Help Typos [ edit | edit source ]
Some versions of Excel can have typos in the F1-help. Here’s an example of a Click handler with the correct parameters:
Iterating Over MultiSelected Cells [ edit | edit source ]
- Works on: Microsoft Excel 2002 SP-2
The following code-snippet writes «YAY!» in each cell selected by the user:
Exporting VBA Code [ edit | edit source ]
- Works on Microsoft Excel 2002 SP-2
The following code provides a very primitive routine to write serializes the VBA code in your modules to files:
Resize a Named Range [ edit | edit source ]
Note that the Resize property of Range objects does not change the size of the range object. It returns a new anonymous Range object. Easiest way to do this is to set the .Name property of the Resized range:
Creating a Named Range [ edit | edit source ]
Named Ranges allow the user to refer to a cell or range of cells by name instead of by their cell address. This name can be used in other cell formulas as well as in VBA (e.g. using the [ SomeName ] ). There are two sorts of named ranges: Workbook Names and Worksheet Names.
To create a Workbook Name you can select the cell you want to name, pull down Insert—>Name—>Define. This will bring up the «Define Name» dialog. Here you can enter the new name for your cell.
The create a Worksheet Name you follow the same procedure but precede the name with Sheetname ! , e.g. Sheet1!InitialValue to create a named-range only visible from within worksheet Sheet1 .
When there are two variables with the same name, one local (Worksheet Name) and one global (Workbook Name), the spreadsheet uses the local variable.
There is no way to visualize a named range. The closest thing is to pull down again Insert—>Name—>Define. , but this method does not show if a variable is a local Worksheet Name or a global Workbook Name.
The named range can be a single cell, part of a row, part of a column or a rectangular group of cells. Each one behaves differently:
- A single cell can be referenced anywhere in the worksheet or, if it’s defined globally (workbook name), anywhere in any worksheet.
- A group of cells composing part of a row can only be referenced in a parallel row. For example, if the named variable is mass and it spans the cells C5:L5, then a reference to mass’ at cell E8 (say, a formula like =mass * (3e8)^2) would take the value at C8, but a reference to mass at cell M9 would return an error
- Similarly, a group of cells composing part of a column can only be referenced in a parallel column. Cells outside the range will return an error
- A group of cells that define a rectangular array of sides greater than one is only useful to be referenced in other worksheets — so, there’s no point in defining them locally (worksheet name). For example, if covmatrix are the cells Sheet1!B2:D4, then if cell Sheet2!C3 has the formula =1/sqrt(covmatrix), then it will return 1/sqrt(Sheet1!C3).
Reading a File [ edit | edit source ]
Reading a file line by line AKA for each line of a file:
- Open at Visual Basic for Applications Reference, msdn.microsoft.com
- Close at Visual Basic for Applications Reference, msdn.microsoft.com
- Line Input at Visual Basic for Applications Reference, msdn.microsoft.com
Writing to a File [ edit | edit source ]
Writing to a file:
Writing the tab-separated content of the current worksheet to a text file, disregarding some of cell content formatting such as percentages:
- Open at Visual Basic for Applications Reference, msdn.microsoft.com
- Close at Visual Basic for Applications Reference, msdn.microsoft.com
- Print # at Visual Basic for Applications Reference, msdn.microsoft.com
File Existence [ edit | edit source ]
Testing whether a file exists:
Directories [ edit | edit source ]
Making a directory:
Removing a directory:
Changing to a directory:
Changing the current drive:
Listing the content of a directory, using a custom filter encompassing two file extensions:
- ChDir at Visual Basic for Applications Reference, msdn.microsoft.com
- ChDrive at Visual Basic for Applications Reference, msdn.microsoft.com
- Dir at Visual Basic for Applications Reference, msdn.microsoft.com
- MkDir at Visual Basic for Applications Reference, msdn.microsoft.com
- RmDir at Visual Basic for Applications Reference, msdn.microsoft.com
Grep [ edit | edit source ]
Searching for a regular expression in the lines of the files of a directory aka grepping:
Clipboard [ edit | edit source ]
Prerequisites: Accessing the clipboard from an Excel sheet requires that a reference to MSForms (Microsoft Forms Object Library) is set in the sheet. You can set the reference by adding and subsequent removing of a user form, via Insert > UserForm in a pop-up menu. To check the presence of a reference, see Tools > References menu.
Placing text on the clipboard:
Getting text from the clipboard:
- DataObject Class at msdn.microsoft.com; contains a section on Visual Basic, whose applicability to Excel VBA is unclear
Range [ edit | edit source ]
A range is a set of cells. The cells in a range do not need to be adjacent. However, the cells in a single range do need to belong to a single worksheet.
Defining a new range:
Iterating a range AKA for each cell in a range:
Iterating rows and iterating columns AKA for each row of a range and for each column of a range, even if discontiguous:
Making an union (a range subsuming both) or intersection (a range covering only cells in common) of two ranges:
Selecting a range:
Activating a cell:
Finding out about a range AKA learning about a range, including the number of cells AKA cell count, the first row, the last row, the first column, the last column, row count, and column count:
- Range Collection at Excel 2003 VBA Language Reference at msdn
- Referring to Multiple Ranges at Excel 2003 VBA Language Reference at msdn
- End Property at Excel 2003 VBA Language Reference at msdn
- Intersect Method at Excel 2003 VBA Language Reference at msdn
- Union Method at Excel 2003 VBA Language Reference at msdn
Worksheet [ edit | edit source ]
To create, access, or delete worksheets, you can use the methods of Worksheet objects. Examples follow.
Obtaining an existing sheet by name or creating it if it does not exist:
- Worksheet Object at Excel 2003 VBA Language Reference at mdsn
- Sheets Collection Object at Excel 2003 VBA Language Reference at mdsn
Searching [ edit | edit source ]
You can search for values in a sheet as follows:
If you want to have a substring match, drop «LookAt:=xlWhole» or use «LookAt:=xlPart».
Cell Formatting [ edit | edit source ]
You can format cells including text color, background color, font properties and border, but also formatting as a number, percent or text from VBA as follows:
Color [ edit | edit source ]
In Excel VBA, RGB colors are plain numbers rather than objects. Some color examples are listed in #Cell Formatting.
Setting the background color of the cells of the 1st column to the row number color index:
Color index in the default palette:
- 0 — Automatic
- 1 — Black
- 2 — White
- 3 — Red
- 4 — Green
- 5 — Blue
- 6 — Yellow
- 7 — Magenta
- 8 — Cyan
- 9 — Dark red
- 10 — Dark green
- 11 — Dark blue
- . etc., through 56
Finding all cells whose text color approaches green:
- Color Property at Excel 2003 VBA Language Reference at msdn
- ColorIndex Property at Excel 2003 VBA Language Reference at msdn
- Colors Property at Excel 2003 VBA Language Reference at msdn
- ColorType Property at Excel 2003 VBA Language Reference at msdn
- PatternColor Property at Excel 2003 VBA Language Reference at msdn
- PatternColorIndex Property at Excel 2003 VBA Language Reference at msdn
Visibility [ edit | edit source ]
Hiding a row (hide a row, hide row):
Hiding several rows at once:
Hiding the rows of the currently selected cells:
Looping over rows that are visible AKA shown AKA not hidden:
Toggling the visibility of rows:
Hiding a column (hide a column, hide column):
Hiding several columns at once:
Hiding the columns of the currently selected cells:
Other tricks pertaining to visibility of columns work in a direct analogy to the examples for rows above.
Hyperlink [ edit | edit source ]
Opening or following a hyperlink (open a hyperlink, follow a hyperlink, open hyperlink, follow hyperlink):
Opening the Wikipedia article for the article title found in the single active cell by opening a put-together URL:
Opening a Wikipedia article per article title in any of the currently selected cells:
Opening a local hyperlink, with a possible pop-up asking for confirmation for security reasons:
Temporary file [ edit | edit source ]
Getting a temporary file, with unclear robustness of the following method, which uses random numbers and tests for file existence:
Command Output [ edit | edit source ]
If you do not mind a popping up console window, here is a way of obtaining output of a command from Excel VBA:
If having a console window popping up is not acceptable and you are okay with creating a temporary file, here is another way of obtaining output of a command from Excel VBA:
Using cmd /c, you can run chains of commands connected using & or | as well:
Dimensions [ edit | edit source ]
Row height and column width:
- RowHeight Property at Excel 2003 VBA Language Reference at msdn
- ColumnWidth Property at Excel 2003 VBA Language Reference at msdn
- StandardHeight Property at Excel 2003 VBA Language Reference at msdn
- StandardWidth Property at Excel 2003 VBA Language Reference at msdn
Working with comment aka note:
Collecting all comments of the sheet into a string:
- Comment Object at Excel 2003 VBA Language Reference at msdn
- Shape Object at Excel 2003 VBA Language Reference at msdn
IsEmpty [ edit | edit source ]
Approximately speaking, tells whether a variable has been initialized and not yet written to.
Can be used to tell whether a cell is empty; the presence of a comment attached to the cell or formatting of the cell does not make a cell non-empty.
- IsEmpty at Excel 2010 VBA Language Reference at msdn
IsNull [ edit | edit source ]
Tells whether an expression is Null, which is distinct from Empty.
Null can be assigned to variant variables; it cannot be assigned to variables dimensioned as strings or integers. Null cannot be assigned to objects, unlike Nothing.
- IsNull at Excel 2013 VBA Language Reference at msdn
Add-Ins at Startup [ edit | edit source ]
Controlling what add-ins Excel opens at startup:
Microsoft Excel 2003: Configure loaded add-ins via Tools -> Add-ins. Their list is mirrored in the following Registry key, but there’s no advantage in editing the Registry:
Microsoft Excel 2002 SP-2:When you start Excel, it may automatically load addins (i.e. those you added from Tools -> Add-Ins). The list of add-ins that get loaded come from the following registry key:
Under this key you may find a list of string-variables:
The values of these variables is the name of the add-in. Excel, on start-up, will attempt to load the add-in in string-variable OPEN first, then OPEN1 (if present), onward until it runs out of such string-variables. It seems like Excel will automatically renumber the keys if they are not consecutive (i.e. OPEN1, OPEN3, OPEN4 will become OPEN1, OPEN2, OPEN3).
Note also the list of add-ins presented when you do Tools -> Add-Ons is, in part, populated by the contents of the following key:
Chart direct from VBA array data [ edit | edit source ]
Charts need not be based on the values in cells of a spreadsheet, but can also be made directly in VBA from an array. The following code makes a chart of the relative frequency of characters in a string, in percent of the total, or normalized to a maximum of unity. There is also an option to sort the display and the content can be changed by modifying the content or sequence of the vRef array. Procedures to remove charts and test the functions are included.
Nuking Retained State [ edit | edit source ]
- Works on: Microsoft Excel 2002 SP-2
- OS: Windows XP
Nuking Excel’s Retained State: Excel remembers all sorts of things between runs: What addins to load, what buttons and menus to display, etc. Sometime you’ll want to clean all of this stuff up and bring Excel back to its factory state.
Nuking Excel Checklist:
- Make sure the following directories are empty:
- C:Program FilesMicrosoft OfficeOffice10xlstart
- C:appsxpapplication dataMicrosoftxlstart
- Nuke the auto-open keys from the registry(as shown below);
- Nuke all .xlbs – For example check here:
- C:appsxpapplication dataMicrosoftExcel
Источник
From Wikipedia, the free encyclopedia
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 Access BASIC and Word BASIC 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]
- ^ «Compatibility Between the 32-bit and 64-bit Versions of Office 2010». msdn.microsoft.com.
- ^ o365devx. «What’s new for VBA in Office 2019». docs.microsoft.com. Retrieved 2022-05-02.
- ^ «Support for VBA Macros». The Document Foundation — LibreOffice. Retrieved 3 January 2023.
- ^ «Reflection Desktop VBA Guide». docs.attachmate.com. Retrieved 2017-07-01.
- ^ «2016 SolidWorks Help – VBA». help.solidworks.com. Retrieved 2016-07-25.
- ^ a b «ACC: Visual/Access Basic Is Both a Compiler and an Interpreter». Microsoft. 2012. Archived from the original on 2012-10-21.
- ^ «How to set up and use the RTD function in Excel». msdn.microsoft.com.
- ^ «Microsoft to Block Office VBA Macros by Default». The Verge. Retrieved 2022-09-26.
- ^ «Visual Studio for Applications». Archived from the original on 2007-12-17.
- ^ «Introducing Visual Studio for Applications». msdn.microsoft.com.
- ^ «Script Happens .NET». msdn.microsoft.com.
- ^ «Microsoft Takes Wraps Off VSA Development Technology». Archived from the original on 2007-12-17.
- ^ a b «VSA scripting in .NET». Archived from the original on 2007-02-11.
- ^ «WWDC: Microsoft updates Universal status of Mac apps». Macworld. 2006-08-07. Retrieved 2007-05-25.
- ^ «What is Microsoft Office and Office 365 – FAQs».
- ^ «The Reports of VBA’s Demise Have Been Greatly Exaggerated».
- ^ «Clarification on VBA Support». Archived from the original on 2008-01-19.
- ^ «Compatibility Between the 32-bit and 64-bit Versions of Office 2010». msdn.microsoft.com.
- ^ «Release notes for Monthly Channel releases in 2017». learn.microsoft.com. Retrieved 2022-11-13.
Excel VBA Online Tutorial — learn VBA Programming, enhance your Excel skills!
Learn Excel VBA programming with our easy to understand Excel VBA Online Tutorial — access examples & illustrations, live codes and downloadable files which will make learning VBA simple and quick for you. The VBA course starts with Excel VBA Basics, teaches how to create your own VBA Procedures & Macros, explains how to use Automation with VBA (Send Email from Excel, Automate PowerPoint, …) and then illustrates how to Connect with Databases (Access).
VBA for Excel
VBA is a programming language used to work with Microsoft Excel, and also with other Microsoft Office applications like Microsoft Word, Microsoft Access, PowerPoint, … and with many third-party applications. VBA stands for Visual Basic for Applications and reference to Excel VBA indicates that the Application is Excel. It is a language which Excel understands and is used to give instructions to Excel to program and automate tasks.
Benefits of VBA
VBA programming is used to get enhanced functionality which might be beyond an Excel spreadsheet;
VBA is used to automate repetitive tasks in Excel;
VBA is used to integrate Excel with other Office applications such as Microsoft Access.
Our Excel VBA Online Tutorial
Learn Excel VBA programming with our easy to understand Excel VBA Online Tutorial — access examples & illustrations, live codes and downloadable files which will make learning VBA simple and quick for you. If you are finding VBA difficult to learn, or if you find it too complicated, or if you feel it is beyond your capacity, then you have come to the RIGHT place. We keep it easy! Our tutorial is in plain language, in English, and will enable you to master Excel VBA effortlessly.
Brief Contents: Excel VBA Basics; VBA Objects; Working with Variables; Conditional Statements; VBA Loops; Application Object; Workbooks & Worksheets; Cells & Ranges in VBA; String & Date Functions; VBA Procedures & Functions; VBA Arrays; Error Handling; Events; Custom Classes & Objects; UserForms; Charts, Shapes, ActiveX & Form Controls; PivotTables with VBA; Automation with VBA (Send Email from Excel, Automate PowerPoint, …); Connect with Databases — ADO, ADOX & DAO;
Methodology: You will create a Free Login Account on our site (‘VBA Tutorial Login’ on the Left Panel), and then Login with your username and password to access our Online Tutorial. You will get complete access to the Excel VBA course, structured in appropriate Sections & Chapters, with Live Codes & Downloadable Excel Files. You can learn VBA from the comfort of your house or office, 24 x 7, without any time limits, explained in a simple and easy manner.
The tutorials are based primarily on Microsoft Excel 2007.
Is the VBA Tutorial for YOU?
The tutorial presumes a basic knowledge of Microsoft Excel for the user, and familiarity with basic Excel concepts and using a Spreadsheet.
We expect the VBA Tutorial to be useful for users who are either beginners in VBA, as well as those already having a reasonable working knowledge of VBA.
Why Us?
Check out what some existing users have to say about our Excel VBA Tutorial (click for all Testimonials):
«Thanks very much. Excellent tutorial … Looked like a nightmare on other sites. This one broke it down and showed it best. Cheers!
«I find your site very informative and written in understandable language.»
«Thank you for sharing your excellent, clear VBA explanations. It saves my time.»
«I have been teaching myself VBA over the past 5 months by incorporating it into many useful projects. I have purchased several well-known books and searched the internet extensively as I’ve encountered problems. I don’t know what took me so long to come across your site, but it is without a doubt, the best site on the web for getting a good handle on VBA. The clear examples and descriptive notes are very informative. You provide much depth while keeping it simple.»
«Good Work! One of the best sites i have come across.!! I was stuck up in a problem fr 3 days….n i got it solved here..!! Many Many thanks :)»
«I was completely taken back by the amount of information and examples that were offered. I stopped writing my code, and I spent over two hours exploring the MANY facets of this site. The whole time, I was saying, » Wow!…. Wow!… Wow!» . Your explanations and examples have helped me a great deal! «
«I’ve been to all kinds of excel schools, addin, books, excel program like … Finding ways to make me understanding excel in shortcut mode. Wanted to know the code and just copy with simple reason about the code. Done. period. I’m thankful for your work … and give me more information if there’s more.»
Get the VBA Advantage Today — learn Excel VBA & Macros, take your Excel skills to the next level!
We want you to come join us, in the marvelous world of vba programming, to discover the magic of vba!
Detailed Contents of Excel VBA Online Tutorial
Sections |
Chapters | Topics |
Excel VBA Basics |
Excel VBA — Introduction |
Programming Languages & Visual Basic; Visual Basic for Applications (VBA), VBA is GUI-based; Visual Basic is not truly an Object-Orientated Programming (OOP) Language; VBA is an Event-driven programming language; Enable VBA / Macros in Excel 2007 & 2003; |
VBE — the VBA Code Editor |
Launch the Visual Basic Editor; Visual Basic Editor components — Code Window, Project Explorer, Properties Window, The Programming Workspace; |
|
Record & Run Macros |
Record and Run Macros using the Excel Macro Recorder — the Record Macro dialog box, Naming a Macro, Assign a Keyboard Shortcut, Store a Macro, Add a Description, Recording a Macro, View, Edit & Run a Recorded Macro, Use Relative References, Limitations of Recording a Macro, Storing a Macro in Personal Macro Workbook; |
|
Starting with VBA, Writing Code |
Basic concepts in brief: Excel VBA Objects, Properties & Methods; Event Procedures in VBA; Visual Basic Editor (VBE); Modules in Excel VBE; VBA Procedures; Creating a sub-procedure; Run or Execute a Procedure; Line Continuation within VBA code; Auto Syntax Check;Comment Text within VBA code; Indenting your VBA code; Using Variables in VBA; Keywords in VBA; Arithmetic Operators; String Operators; Using Message Box in your code; Examples of writing vba code; |
|
Message Box & Input Box |
Using Message Box in vba code — MsgBox Function; Using Input Box in vba code — InputBox Function, Application.InputBox Method, Accepting formulas in InputBox, Accepting a cell reference as a Range object in InputBox; |
|
Excel VBA Objects |
Working with Objects |
VBA Objects; The Excel Object Model; Access an Object / Access a Single Object from its Collection; Properties and Methods of Objects; Working with Objects in Excel VBA — Excel VBA IntelliSense, Using With…End With Statement to refer to Objects, Using Variables in VBA, Keywords in VBA, Assign an Object to a Variable, using the Set Keyword; |
Working with Variables |
Declare Variables in VBA |
Declaring Variables — variables are initialized to a default value, assign a value to a variable, assign an object reference, using Option Explicit; Valid and Invalid Declaration of Variables; Dim statements declared at 3 basic levels — Procedure Level, Module Level, Project Level; Initialize variables; Static Statement; ReDim Statement to Resize Dynamic Array; Variable Names — Naming Conventions for Variables; Variable Data Types; |
Conditional Statements |
If…Then…Else Statements |
If…Then…Else Statements — Multiple line statements, Nesting, using NOT Operator with IF statement, Single line If…Then…Else Statements, Select…Case, compared to If…Then…Else Statements; |
Select…Case Statement |
Select…Case Statement (VBA) — using the To keyword to specify the upper and lower range of values, using the Is keyword (with a comparison operator) to compare values, using a comma to separate multiple expressions or ranges in each Case clause, Option Compare Setting, Nesting, GoTo statement, compared to If…Then…Else Statements; |
|
Excel VBA Loops |
Excel VBA For & Do Loops |
The For Loop — the For … Next Statements, the For Each … Next Statements, Nesting Loops, the Exit For Statement; The Do While Loop — the Do While … Loop Statements, the Do … Loop While Statements, the Exit Do Statement; The Do Until Loop — the Do Until … Loop Statements, the Do … Loop Until Statements, the Exit Do Statement; |
Excel Application Object |
Application Object, Properties & Methods |
Excel VBA Application Object; Instances where using the Application qualifier is required — Height, Width and WindowState Properties, DisplayFullScreen Property, DisplayFormulaBar Property, Calculation Property, EditDirectlyInCell Property, ScreenUpdating Property, DisplayAlerts Property, DefaultFilePath Property, Quit Method, Application.OnTime Method, ActivateMicrosoftApp Method, Application.GetOpenFilename Method; When it is not required to specify the Application qualifier — ActiveCell Property, ActiveWindow Property, ActiveWorkbook Property, ThisWorkbook Property, ActiveSheet Property, ActiveChart Property, ActivePrinter Property, Selection Property, Sheets Property, Range Property, Calculate Method; |
Application.OnTime VBA, Schedule Macros |
Excel Application.OnTime Method — Scheduling OnTime Events; Stop or Cancel a Running Procedure (using the OnTime method); |
|
Excel VBA Workbooks |
Workbook Object, Properties & Methods |
Reference a Workbook object — Workbooks.Item Property, ActiveWorkbook Property, ThisWorkbook Property; Open, Add, Copy & Close Workbooks — Workbooks.Open Method, Workbooks.Add Method, Close Method, OpenDatabase Method, SaveCopyAs Method; Saving Workbooks — Workbook.Save Method, Workbook.Saved Property; Often used Methods & Properties of the Workbook Object — Workbook.Activate Method, PrintPreview Method, Workbook.SendMail Method, Workbook.ActiveSheet Property, ActiveChart Property, FileFormat Property, Name Property, Password Property, Path Property; |
Excel VBA Worksheets |
Worksheet object, Properties & Methods |
The Worksheet Object, Sheets Object, Chart Object, 4 types of sheets — worksheet, chart sheet, macro sheet,dialog sheet; Reference a Worksheet object — Item Property, The Active Object, Code Name and Sheet Name; Activate or Select a Worksheet — ActiveSheet Property, Activate Method, Select Method; Adding & Naming Worksheets — Add Method, Default worksheet names on creating a new workbook, Name property; Copy a Worksheet, Move or Change Worksheet Sequence, Hide or Display Worksheets, Remove or Delete a Worksheet — Copy Method, Move Method, Visible Property, Delete Method; Worksheet Page Layout & Views — PageSetup Property, PrintPreview Method, DisplayPageBreaks Property, View Property; Calculating Worksheets — Calculation Property, Calculate Method; Speed up your VBA Code by Turning off Screen Updates and Automatic Calculations — Screen Updates and Automatic Calculations, CalculateBeforeSave Property, EnableCalculation Property; |
Run Macros on Protected Worksheet |
Run VBA Macros on Protected Worksheet; Unprotect & Protect; Error Handler; UserInterfaceOnly argument in the Protect method; Run macro on protected worksheet, code remaining visible & editable, but protection password hidden; Using the UserInterfaceOnly argument to Enable Auto Filter; Using UserInterfaceOnly argument to Allow Grouping; Worksheet.Protect Method; |
|
Excel VBA Cells & Ranges |
Referencing Cells & Ranges — 1 |
Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address — Range Object, Range property, Shortcut Range Reference, Cells Property, Item property, Columns Property, Rows Property, Accessing a worksheet range with vba code (Referencing a single cell, Referencing a range of cells, Referencing Rows or Columns, Relative Referencing), Range.Row Property, Range.Column Property, Range.Address Property; Activate & Select Cells; The ActiveCell & Selection — Select method, ActiveCell Property, Selection property, Activate Method; Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method — EntireRow Property, EntireColumn Property, Insert Method; |
Referencing Cells & Ranges — 2 |
Ranges, Union & Intersect — Union Method, Intersect Method, using Intersect method with worksheet change or selection change events; Resize a Range — Offset & Resize properties of the Range object; Contiguous Block of Cells, Collection of non-contiguous ranges, Cells Meeting a Specified Criteria, Used Range, Cell at the End of a Block / Region — Using the Areas Property, CurrentRegion Property, SpecialCells Method, UsedRange property, End Property, find Last Used Row in a worksheet; |
|
Find Method in Excel VBA |
Find Method in Excel VBA; Find multiple occurrences of an item or value in a range; Using Find Method to do VLookUp; Using Find Method to Search for a Date; |
|
VBA — Last Used Row & Column |
Use End(xlUp) to determine Last Row with Data, in one column; Use End(xlToLeft) to determine Last Column with Data, in one row; UsedRange property to find the last used row number in a worksheet; UsedRange property to find the last used column number in a worksheet; UsedRange property to find number of used rows in a worksheet; UsedRange property to find number of used columns in a worksheet; UsedRange property to find the first used row number in a worksheet; UsedRange property to find the first used column number in a worksheet; Use End(xlDown) to determine Last Row with Data, at the End of a Block in a column; Use End(xlToRight) to determine Last Column with Data, at the End of a Block in a row; FIND method to determine Last Row with Data, in a worksheet; FIND method to determine Last column with Data, in a worksheet; SpecialCells method to find Last Used Row in worksheet; SpecialCells method to find Last Used Column in worksheet; |
|
Text, String & Date Functions |
Excel Text & String Functions — 1 |
Excel VBA String Functions for Finding and Replacing Text, with Examples: LEFT, RIGHT, MID, LEN, REPLACE; InStr & InStrRev Functions (VBA); |
Excel Text & String Functions — 2 |
Excel VBA String Functions: SPLIT, JOIN, CONCATENATE — Excel VBA Functions to Split a String into Substrings, and Join an Array of Substrings to form a String, with Examples. |
|
Functions — CODE & CHAR / Asc & Chr |
Excel Text and String Functions: Excel CODE & CHAR Functions, VBA Asc & Chr Functions, with examples — Changing case (uppercase / lowercase) of alphabets in a string, format or manipulate data with ANSI codes; |
|
ASCII & ANSI Code, Extended ASCII characters |
ASCII Code; ASCII to Extended ASCII characters (8-bit system) and ANSI Code; Extended ASCII characters (8-bit) and UNICODE; The Windows SDK provides function prototypes in generic, Windows code page (ANSI) and Unicode versions; Excel uses ANSI code system for Windows computers; ASCII Non-Printing Control Codes Chart; ASCII Printing Characters Chart; Extended ASCII Printing Characters Chart; |
|
Column No. to Letter, Column Letter to No. |
VBA Codes to Convert Excel Column Number to corresponding Column Letter; VBA Codes to Convert Excel Column Letter to corresponding Column Number; |
|
VBA Convert to UpperCase / LowerCase |
Worksheet vba codes for: Convert Text and Cells with Formulas to UpperCase; Convert Text and Cells with Formulas to UpperCase; Convert Text and Cells with Formulas to UpperCase; Convert Text to UpperCase; |
|
Excel VBA Dates & Time, Format Function |
Excel VBA Dates & Time — Excel Dates Equate to Serial Numbers, Date Data Type in VBA, System’s Locale settings vs. Code Locale, Format specified in your computer’s regional settings; Format Function in VBA — Predefined Named Date/Time Formats, System-defined Format, Predefined Named Numeric Formats, User-Defined Number Formats, User-Defined Date & Time Formats, User-Defined String Formats, Multiple Sections for User-defined Formats; |
|
Excel VBA Date & Time Functions |
VBA DateSerial Function; DateValue Function; TimeSerial Function; TimeValue Function; IsDate Function; CDate Function; DateAdd Function; DateDiff Function; DatePart Function; Date Function; Now Function; MonthName Function; Day Function; Month Function; Year Function; Hour Function; Minute Function; Second Function; WeekDay Function; WeekdayName Function; Find Method to Search for a Date; |
|
Custom Number Formats, Date Formats |
Excel Home Tab, Format Cells dialog box; VBA, NumberFormat property; Number Codes; Specify Font Color; Four Sections of Code; Specify Conditions; Custom Date & Time Formats; |
|
Excel VBA Procedures |
Subs & Functions, Placement in Modules |
Sub procedures (Event Procedures & User Created), Function Procedures (Built-in & User-defined) & Property Procedures; Naming Rules & Conventions for Procedures; VBA Procedures Scope — Public vs Private; Placement of Macros / Sub procedures in appropriate Modules — Standard Code Modules, Workbook module, Sheet Modules, UserForm Modules, Class Modules; Calling Procedures — Calling Sub procedures in the Same Module, Calling Functions in the Same Module, Calling Procedures in Outside Modules; Executing Procedures — Executing Function Procedures, Executing Event Procedures, Executing Sub Procedures; |
Pass Arguments to Procedures, ParamArray |
Argument Data Types; Passing Arguments By Value; Passing Arguments By Reference; Optional Arguments; Pass an Arbitrary or Indefinite Number of Arguments — Parameter Arrays (ParamArray); |
|
VBA — Empty, ZLS, Null, Nothing, Missing |
Empty, Blank, ZLS (zero-length string), Null String & vbNullString; IsEmpty Function; VarType Function; Null; IsNull Function; Nothing; Missing; IsMissing function; |
|
Excel VBA Arrays |
Excel VBA Arrays |
VBA Arrays; Declare Arrays, Sizing an Array, Determining the Upper and Lower Bounds; One-Dimensional and Multi-Dimensional Arrays; Fixed-size and Dynamic Arrays; ReDim Statement to Resize Dynamic Array; use the ‘Preserve’ Keyword with the ReDim statement; Excel VBA Functions — SPLIT a String and return an Array of Substrings, JOIN an Array of Substrings to form a String; Create a 200-Year Calendar in VBA, using Arrays with Loops; ParamArray (Parameter Array); |
Error Handling & Debugging |
Error Handling in VBA |
VBA Erros & Error Handling, Error Handling Setting in VBE, Error Handler, On Error Statements, Using an Exit Statement, Error Handling in Nested Procedures & The Resume Statement, Get Information from the Error Object, Raise Method of the Err Object — Generate a Run-time error. |
Debugging Tools in VBE |
Debug Code by using a Message Box, Use Breakpoints to Debug Code, Using Break Mode to Debug Code, Stepping Through Code, Debugging Views — Immediate Window, Locals Window, Watch Window, Call Stack. |
|
Excel VBA Events |
Excel VBA Built-in Events |
Excel VBA Events; Event Procedures; Built-in Event procedures & Custom events; Excel events broadly classified — Workbook events, Worksheet events, Chart events, UserForm events, Application events, Events not associated with objects; |
Worksheet Change Event |
Worksheet_Change Event; Target parameter; Preventing Event Loops with Application.EnableEvents = False; |
|
Worksheet Selection Change Event |
Worksheet_SelectionChange Event; Preventing Event Loops with Application.EnableEvents = False; |
|
Custom Classes & Objects |
Custom Classes & Objects, Custom Events |
Excel VBA Custom Classes & Objects — Insert a Class Module, Name a Class Module, Instancing Property of a Class Module, Instantiate a Class Object, Create Class Properties, Using Property Procedures to Create Properties (Property Get, Property Let, Property Set); Custom Class Events — Define a Custom Event, Raise an Event, External Code to Raise the Event, Create an Event Procedure; |
ActiveX & Form Controls, AutoShapes |
ActiveX & Form Controls, AutoShapes |
Built-in Excel Data Form; Using ActiveX controls, Form controls & AutoShapes in Excel Worksheet; Shape object & OLEObject object; ActiveX Controls in VBA; Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet; Illustrating Form Controls, ActiveX Controls & AutoShapes — Button (Form Control) & Command Button (ActiveX Control), Check Box (Form Control or ActiveX Control), List Box & Combo Box (Form Control / ActiveX Control), Option Button (Form Control or ActiveX Control), Toggle Button (ActiveX Control), ScrollBar & SpinButton Controls(Form Control or ActiveX Control), TextBox (ActiveX Control), Label (Form Control or ActiveX Control), Illustrating Auto Shapes & Add a connector; |
UserForms in Excel VBA |
UserForm Basics, Add Controls |
UserForms in Excel VBA; Create a UserForm; UserForm ToolBox Controls — A Snapshot; UserForm Basics; Trapping UserForm Events; Add Controls to a UserForm — using the Add Method; |
UserForm and Controls — Properties |
Design-Time, Run-time and Break-time; Setting control properties with vba; Basic Properties common to the UserForm and most Controls — Name Property, Caption Property, Height & Width Properties, Left & Top Properties, Value Property; Other Properties common to the UserForm and most Controls — Accelerator Property, Alignment Property, AutoSize Property, BackColor Property, BackStyle Property, BorderColor Property, BorderStyle Property, ControlSource Property, ControlTipText Property, Enabled Property, Locked Property, Font Object, ForeColor Property, MouseIcon Property, MousePointer Property, Picture Property, PicturePosition Property, SpecialEffect Property, TabIndex Property, TabStop Property, Visible Property, WordWrap Property; Specifying Color in Properties Window; Applicability of Properties to UserForm and its Controls — A SnapShot; |
|
Label, TextBox & CommandButton |
Label Control; CommandButton — Click event; TextBox — AutoTab Property, EnterKeyBehavior Property, MaxLength Property, MultiLine Property, PasswordChar Property, ScrollBars Property, Text Property; |
|
ComboBox & ListBox |
Difference between ListBox and ComboBox; Key Properties of ComboBox and ListBox — AddItem Method, BoundColumn Property, Clear Method, Column Property, ColumnCount Property, ColumnHeads Property, List Property, ListCount Property, ListIndex Property, ListRows Property, MultiSelect Property, RemoveItem Method, RowSource Property, Selected Property, Style Property, TextColumn Property; Add Items/Data to (Populate) a ListBox or ComboBox — Setting the RowSource property of a ListBox or ComboBox in a UserForm, Populate a ComboBox or ListBox from an Array, Populate a ComboBox or ListBox with AddItem method, Populate a multi-column ComboBox or ListBox using AddItem method and List & Column properties, Populate a multi-column ListBox from a worskheet range, using AddItem method and List property, Add a new item/row to the list if ComboBox is bound to data in a worksheet; Extract ListBox & ComboBox Items, with VBA — Display selected ComboBox item in TextBox, Copy selected ComboBox item to a worksheet range, Copy ComboBox item determined by its position, to a worksheet range; Delete ListBox rows using the RemoveItem Method; |
|
CheckBox, OptionButton, ToggleButton |
CheckBox — Value property, TripleState property; OptionButton — GroupName property, using a Frame Control, Value property; Difference between CheckBox and OptionButton; ToggleButton; |
|
Frame, MultiPage & TabStrip |
Frame Control; MultiPage Control — Dynamically Add/Remove a Page, Dynamically Access an individual Page, Create a wizard using a Single UserForm and MultiPage control; TabStrip Control — Dynamically Add/Remove a Tab, Difference between a MultiPage control and TabStrip control, Selecting a Tab; |
|
ScrollBar & SpinButton |
ScrollBar Control — SmallChange & LargeChange Properties, Min and Max Properties, Orientation Property; SpinButton Control — SmallChange & Min & Max & Orientation Properties, Difference between ScrollBar & SpinButton controls; |
|
Image & RefEdit |
Image Control — LoadPicture function, PictureSizeMode Property, PictureSizeMode Property, PictureAlignment Property, Use LoadPicture property with GetOpenFilename Method; RefEdit control; |
|
Charts in Excel VBA |
Add a Chart, Chart & ChartObject objects |
Charts in Excel VBA; Worksheet & Chart Sheet in Excel — Chart objects in VBA; Add a Chart — Charts.Add Method, ChartObjects.Add Method; ChartObject object — Commonly used Properties & Methods; Chart object — Commonly used Properties & Methods; |
Chart Elements: Chart Title, Chart & Plot Area, Axes |
Chart Title — Commonly used Properties & Methods of the ChartTitle object, Child Objects for the ChartTitle Object; Chart Area — Commonly used Properties & Methods of the ChartArea object, Child Objects for the ChartArea Object; Plot Area — Commonly used Properties & Methods of the PlotArea object, Child Objects for the PlotArea Object, PlotArea Alignment , ChartTitle Alignment, AxisTitle Alignment, Legend Alignment; Chart Axis — Axes object & Axis object, Tick Marks & Gridlines, Commonly used Properties & Methods of the Axis object, Properties & Methods of the AxisTitle object, Properties & Methods of the TickLabels object, Child Objects for the Axis Object; |
|
Chart Elements: Chart Series, Data Labels, Legend |
Chart Series — SeriesCollection object & Series object, Commonly used Properties & Methods of the Series object, Child Objects for the Series Object, ErrorBars & LeaderLines, Combination Chart; DataLabels Object & DataLabel Object — Commonly used Properties & Methods of the DataLabels Object / DataLabel Object, Child Objects for DataLabels Object / DataLabel Object; Chart Legend — LegendKey & LegendEntry, Commonly used Properties & Methods of the Legend object, Child Objects for the Legend Object. |
|
Border / ChartFillFormat / Interior / Font Objects |
Child Objects commonly used with Chart Elements — Border Object, ChartFillFormat Object, Interior Object & Font Object with Properties & Methods. |
|
ChartFormat object, Formatting, 3D Charts |
Line, fill & effect formatting for chart elements: FillFormat object — Setting ForeColor & BackColor, Setting a Solid Fill, Setting Gradient Type, Gradient Stops, Setting Pattern, Setting Texture, Setting Picture for the Fill; LineFormat object — Setting ForeColor & BackColor, Setting Style or Dash Style, Setting Pattern, Line Arrowheads, Transparency & Weight Properties; ShadowFormat object; GlowFormat object; SoftEdgeFormat object; ThreeDFormat object — Manipulating 3-D Charts; |
|
Create Line, Column, Pie, Scatter, Bubble charts |
Create an Embedded Chart — Line with Markers; Creating a Clustered Stacked Column Chart; Create a Clustered Stacked Bar Chart displaying Variance between Series; Pie Chart; XY Scatter Chart & Bubble Chart — Single series with X & Y values, Multiple series where all series share the same Y values with distinct X values, Manipulate both X & Y error bars; |
|
Excel Pivot Tables with VBA |
Create Pivot Table using VBA |
Use VBA to Create and Customize PivotTable & PivotChart reports; The PivotTableWizard method; |
Referencing Pivot Table Range |
TableRange1 Property and TableRange2 Property; PivotField.LabelRange Property and PivotItem. LabelRange Property; RowRange Property and ColumnRange Property; PivotTable.DataBodyRange Property; DataLabelRange Property; PageRange Property; PivotField.DataRange Property and PivotItem. DataRange Property; PivotTable.PivotSelect Method; Intersect Method; |
|
Reference Pivot Fields & Items |
Using the PivotTable.PivotFields Method to access a Pivot Field; PivotTable.ColumnFields Property to access a column field; PivotTable.RowFields Property to access a row field; PivotTable.DataFields Property to access a data field; PivotTable.PageFields Property to access a page field; Reference PivotItem in a PivotField; PivotTable.HiddenFields Property to return hidden fields; PivotTable.PivotSelect Method to Select a part of the PivotTable; |
|
Pivot Table Move & Copy |
Address of Pivot Table; Move PivotTable to a new location; Copy a PivotTable and paste as data or values or paste as a PivotTable; |
|
Pivot Table Layout & Design |
Layout Forms for PivotTable report, column header and row header; Hide or Display Subtotals; Subtotal Location, Inserting blank lines, Show/hide GrandTotals & Grand Total Name, Set Number Format; Pivot Table Styles — Style Gallery; PivotTable Style Options — Row Headers, Column Headers, Banded Rows & Banded Columns; |
|
Pivot Table Properties & Settings |
Get data from a PivotTable using VBA — PivotTable.GetPivotData Method; Disable or Enable DrillDown of PivotTable Fields; Display the PivotTable FieldList; Sort Fields in Ascending order in the PivotTable FieldList; Return the Parent object of a PivotTable object; Allow PivotTable Update only Manually; PivotTable.Name Property returns the name of a PivotTable object; PivotTable Print Settings — PivotTable.PrintTitles Property, PivotTable. RepeatItemsOnEachPrintedPage Property, Repeat specific rows at the top or columns on the left while printing a PivotTable report, PivotTable.PrintDrillIndicators Property; Save the PivotCache data while saving the workbook; Create a new PivotTable, each on a new worksheet, for each item of a Page field; Return the data source of a PivotTable report; Include hidden page field items in subtotals and totals; Pivot Table versions & Excel version; |
|
Refresh Pivot Table & Cache |
PivotCache.Refresh Method to Refresh the Cache of the Pivot Table; PivotTable.RefreshTable Method to update the PivotTable report; Automatically refresh Pivot Tables in all worksheets on opening a workbook; Return the Date when PivotTable was last refreshed, and Name of the user who refreshed; |
|
Group Items, Data & Date Values |
Group Date Values in a PivotTable report, using the Group method; Group Date Values by Weeks; Group Numeric Items; Group Specific Text Field Items; |
|
Sort Fields, Values & Dates, Custom Lists |
PivotField.AutoSort method — set sort order of a PivotTable field; Range.Sort Method — to sort a range of values in a PivotTable report; Set the sort order manually; Sort a PivotTable report using Custom Lists — Application.AddCustomList Method, Application.DeleteCustomList Method, Application.GetCustomListContents Method, Application.GetCustomListNum Method, SortUsingCustomLists Property; |
|
Filter Data, Items, Values & Dates |
PivotField.AutoShow method — to display the Top or Bottom items in a PivotTable Field; PivotFilters.Add Method — to add new filters to a PivotTable report; Manual Filter; Clear Filters; PivotTable.AllowMultipleFilters Property — apply multiple filters to a single PivotField; |
|
Summary Functions, Custom Calculations |
Pivot Table Summary Functions — xlAverage, xlCount, xlCountNums, xlMax, xlMin, xlProduct, xlStDev, xlStDevP, xlSum, xlVar and xlVarP; Pivot Table Custom Calculations — xlNoAdditionalCalculation, xlDifferenceFrom, xlPercentOf, xlPercentDifferenceFrom, xlRunningTotal, xlPercentOfRow, xlPercentOfColumn, xlPercentOfTotal and xlIndex; |
|
Insert Calculated Fields, Create Formulas |
Pivot Table Calculated Fields — CalculatedFields.Add Method; Pivot Table Calculated Items — CalculatedItems.Add Method, PivotTable.ListFormulas Method; |
|
Create Pivot Table Charts |
Create a PivotChart based on an existing PivotTable report; Add embedded chart based on an Excel Database; Create a Chart (add a new chart sheet) based on an Excel Database; Create an embedded PivotChart based on an existing PivotTable report; |
|
Automation with VBA |
Automate Microsoft Word from Excel |
Automating an Office Application — Automation Process, Early Binding & Late Binding in Automation, Adding a reference to the Object Library, Built-in Constants and their Numerical Values, The Getobject function and CreateObject function; Automating Word from Excel; |
Automate Microsoft Outlook from Excel |
Create a new instance of the Outlook application; Using the Application.GetNamespace Method; Reference Existing Outlook Folders and Create New Folders in Automation; Create New Outlook Items and Reference Outlook Items; NameSpace.GetDefaultFolder Method; Folders.Add Method; Items.Add Method and the Application.CreateItem Method; Using the Find and FindNext methods to search a folder; Using the Restrict Method; |
|
Export contacts from Outlook to Excel |
Export contacts from Outlook to Excel — automate in vba using Early Binding and Late Binding; Export contacts from a specific Contact Items Folder or from the default Contact Items Folder to an Excel Worksheet; |
|
Import Contacts from Excel to Outlook |
Import Contacts from Excel to Outlook — automate in vba using Early Binding and Late Binding; Import data from an Excel Worksheet to the specified Contacts folder or to the default Contacts folder; |
|
Automate Outlook, Send Email from Excel |
Sending Email from Excel using Outlook — automate in vba using Early Binding and Late Binding; Send text, Send contents from the host workbook’s worksheet range as Mail Body, Send an attachment with the mail; Send multiple mails to ids sourced from the Host Workbook’s sheet; Copy the Host Workbook or Create a New Workbook, Add a New Sheet and Copy-Paste a Range to the Workbook, then send as an attachment with the mail; Find a mail item in the Inbox folder meeting a specified criteria, delete or add attachment, forward it to a specific email id, and move the mail item to a newly created mail folder; |
|
Automate PowerPoint from Excel Automate Microsoft PowerPoint from Excel using vba & Run a Slide Show; Create a new PowerPoint ppt of 4 sli |
des with sound clips and chart, run & view the slide show, automatically close & quit the PowerPoint application; |
|
Connect with Databases (ADO) |
Microsoft Access: ADO Library |
Connect with Databases using DAO, RDO and ADO Objects; ADO Objects & Programming model; Connecting to a Data Source (viz. Microsoft Access) using the ADO Connection Open Method; The Connection Object; Establish Connection to a Data Source; Access records from a database table; The ADO Recordset Open Method, to open an ADO Recordset object; Create a new record using the Recordset Object’s AddNew method; Update Method (ADO Recordset); Close & Delete Methods; Moving between Records in a Recordset; Count the number of Records in a Recordset; Access fields in a Recordset; |
Execute SQL statements — ADO |
Microsoft Access — Use ADO to Execute SQL statements to Manage your Database; SQL Commands explained; Using the ADO connection Execute method to execute the specified query and SQL statements; Use the OpenSchema Method to access information about database tables and columns; Create a database table using ADO with SQL statements; ADO Find Method to Find or Locate a specific Record; ADO Filter Property to FilterRecords; |
|
Import / Export Data, Access to Excel |
Using ADO to Import data from an Access Database Table to an Excel worksheet (your host application); Using ADO to Export data from Excel worksheet (your host application) to Access Database Table; |
|
Connect to Access from Excel — ADOX |
Create an Access Database using ADOX; ADOX Table Object & Tables Collection — Properties & Methods; ADOX Column Object & Columns Collection — Properties & Methods; Reference & Delete Database Tables and Columns and Reference & Edit Field Properties using ADOX; Create an Index using ADOX; Create Relationship between Tables using ADOX; ADO Command Object, ADOX View Object, Parameter Queries, Create & Execute Stored Queries / Action Queries with ADOX; |
|
Connect with Databases (DAO) |
Connect to Access from Excel — DAO |
DAO Objects & Programming model; The DBEngine object; Workspace Object & Workspaces Collection; DAO Databases; Tables of a DAO Database; Fields / Columns of a Table; Recordset & Records of a DAO Database Table; |
Create Index & Relationships, Exceute Query |
Create an Index using DAO; Create Relationship between Fields of Database Tables using DAO; Create and Exceute a Query, including Action & Parameter Query, using DAO; |
|
Import / Export Data from Access to Excel |
Import data from an Access Database Table to an Excel worksheet (your host application); Export data from Excel worksheet (your host application) to an Access Database Table; |
Microsoft Excel is a deep program rich in features and functionality. One of the most powerful features of Excel is the ability to write programs in Visual Basic for Applications that run «behind» your worksheets to turn Excel into a calculation-oriented development platform for creating special purpose spreadsheets which can function as applications in their own right.
Service Pack[edit | edit source]
A service pack (in short SP) is a collection of updates, fixes or enhancements to a software program delivered in the form of a single installable package.
A service pack can be incremental, which means it only contains the updates that were not present in the previous service packs or, it can be cumulative, which means it includes the contents of all its predecessors. In the case of Microsoft’s products, an incremental update was called a service release. For example, Office 2000 must be upgraded to service release 1 (SR-1) before one can install SP2.
Macro Security[edit | edit source]
Macro security settings are located in the Trust Center. However, if you work in an organization, your system administrator might have changed the default settings to prevent anyone from changing any settings and execute macros.
Macro Recording[edit | edit source]
A great way of learning about Excel VBA is using its macro recording function. With the function, you tell Excel to start recording, then perform various steps as if you were working without a macro recorder, and finally, tell Excel to stop recording. VBA code corresponding to what you did using Excel GUI has been recorded by Excel. While the code often cannot be meaningfully used without a modification, by starting from it and modifying it you can save a lot of time that would otherwise be spent reading the VBA documentation.
Menu paths:
- Excel 2000, 2003: Tools > Macro > Record New Macro.
- Excel 2007: View (tab) > Macros (group) > down-pointing triangle below Macros button > Record Macro
- Excel 2007: Developer (tab) > Code (group) > Record Macro
Links:
- Use Microsoft Office Excel 2007 macros to speed up work at microsoft.com
- Create a macro (Excel 2003) at microsoft.com
- Record and use Excel macros (Excel 2000) at microsoft.com
Enabling Developer tab[edit | edit source]
Developer tab allows you to insert various user interface controls such as buttons. In order to use it, you first have to enable it.
Menu paths to enable the tab:
- Excel 2007: round Office button > Excel Options (button at bottom) > Popular > Show Developer tab in the Ribbon (check box)
- Excel 2010: File (tab) > Options (button) > Customize Ribbon (button) > Developer (check box)
Links:
- How to: Show the Developer Tab on the Ribbon for Excel 2007 at microsoft.com
- How to: Show the Developer Tab on the Ribbon for Excel 2010 at microsoft.com
Making an XLA[edit | edit source]
- Works on: Excel 2002 SP-2, Excel 2000 SR-1
An XLA is one way to make a VBA code-library. It’s basically just a normal spreadsheet(.xls file) but has its worksheets hidden. Here’s how to create a new one:
- New Workbook
- Save-As …Name it whatever
- Hit Alt-F11
- In the Project-tree, select VBAProject(whatever.xls)/ThisWorkbook
- Hit F4 to get Properties View
- Find Property IsAddin and set to True
- Hit Save
- Close Excel
- Rename whatever.xls to whatever.xla
Alternatively, you can use Save As / Excel AddIn.
Accessing the Registry[edit | edit source]
- Works on: Microsoft Excel 2002 SP-2
This recipe is for reading/writing keys local to your application—this is to provide persistent settings for your VBA app. It does not cover arbitrary access to the Registry (i.e. looking at any key).
The VBA sub/functions are SaveSetting
and GetSetting
. You can type the following into the Immediate window to get a feel for how these work:
SaveSetting "MyApplicationName", "MyConfigSection", "MyKeyName", "Hello World" MsgBox GetSetting("MyApplicationName", "MyConfigSection", "MyKeyName")
If you want to iterate over all keys in a given section you can do so as follows:
Sub ShowAllKeys() Dim mySettings As Variant mySettings = GetAllSettings("MyApplicationName", "MyConfigSection") If Not IsEmpty(MySettings) Then Dim counter As Integer For counter = LBound(mySettings) To UBound(mySettings) Dim keyname As String: keyname = mySettings(counter, 0) Dim keyval As String: keyval = mySettings(counter, 1) MsgBox keyname & "=" & keyval Next End If End Sub
You can also delete a registry key as follows:
DeleteSetting "MyApplicationName", "MyConfigSection", "MyKeyName"
FYI: Excel/VBA sticks this in the following registry location:
MyComputerHKEY_CURRENT_USERSoftwareVB and VBA Program SettingsMyApplicationNameMyConfigSection
…where MyApplication
and MyConfigSection
are whatever you specified in your SaveSettings
call.
They end up in HKEY_CURRENT_USERSoftwareVB and VBA Program SettingsMyApplicationNameMyConfigSection.
[edit | edit source]
- Works on: Microsoft Excel 2002 SP-2
Make the following call from VBA:
Application.DisplayAlerts = False
Making Cells Read-Only[edit | edit source]
- Works on: Microsoft Excel 2002 SP-2
Sub ProtectMe() Range("A1:IV65536").Locked = False Range("A1").Locked = True ActiveSheet.Protect Password:="Test" End Sub
Finding Non-Empty Portion of Worksheet[edit | edit source]
A Worksheet has a maximum size of 65536 rows by 256 columns. However if you want to iterate over all cells you probably don’t want to visit all of the empty ones. For this purpose the Worksheet provides the UsedRange property. For example:
ActiveSheet.UsedRange.Rows.Count
tells you how many non-empty rows are in the given worksheet. Empty rows which are in between the first and last used row are counted as well. Example: If a given Worksheet has entries in cells A7 and B16, used range is considered to be A7:B16, which counts for a total of 10 rows.
Using Events[edit | edit source]
- Works on: Microsoft Excel 2002 SP-2
Consider the following class definition—Assume its a class called CMyClass:
Option Explicit Dim WithEvents mySheet As Worksheet Public Sub Init(aWS as Worksheet) Set MySheet = aWS End Sub Private Sub mySheet_SelectionChange(ByVal Target As Range) Dim MyRange As Range For Each MyRange in Target Debug.Print CStr(MyRange) Next End Sub
The main ideas here are:
- By declaring mySheet WithEvents, you’re saying that CMyClass is listening to mySheet’s events.
- By declaring the member sub mySheet_SelectionChange you’re indicating how an instance of CMyClass should react if mySheet experiences a selection change (i.e. the user selects a new cell or range of cells); The general pattern for events is sub memberVarName_EventName(params).
- You can disconnect the eventing between the given worksheet and CMyClass by setting mySheet = nothing;
- You can create classes that throw events of your design using:
- You would declare at the top of the class: Public Event SomeNiceEventName(YourFavoriteParam1 as WhateverType, etc…),
- You could then raise that event (i.e. firing it to whatever listeners your class has) using RaiseEvent SomeNiceEvent(«Some nice event happened.»);
- VBA in Excel doesn’t like the letters r or c used as variables. Those letters mean ‘row’ and ‘column’ elsewhere.
A little more detail is given here: [1]
Caveat: Uncaught Exceptions[edit | edit source]
Caveat: Uncaught exceptions in event-handlers cause VBE to mysteriously reset. If you are causing an uncaught exception in an event-handler, you probably won’t get an error popup. Instead, VBE will just reset. For this reason you should make sure you’re catching exceptions in all of your event handlers.
Caveat: Online-Help Typos[edit | edit source]
Some versions of Excel can have typos in the F1-help. Here’s an example of a Click handler with the correct parameters:
Private Sub clicksrc_Click(ByVal Ctrl As Office.CommandBarButton, CancelDefault As Boolean) MsgBox "I got a click!" End Sub
Iterating Over MultiSelected Cells[edit | edit source]
- Works on: Microsoft Excel 2002 SP-2
The following code-snippet writes «YAY!» in each cell selected by the user:
For Each Cell in Selection Cell.Value = "YAY!" Next
Exporting VBA Code[edit | edit source]
- Works on Microsoft Excel 2002 SP-2
The following code provides a very primitive routine to write serializes the VBA code in your modules to files:
Option Explicit Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim objModule As Object On Error Resume Next For Each objModule In ThisWorkbook.VBProject.VBComponents DoEvents If objModule.CodeModule.CountOfLines > 0 Then objModule.Export objModule.Name & ".bas" End If Next objModule End Sub
Resize a Named Range[edit | edit source]
- Excel 2003
Note that the Resize property of Range objects does not change the size of the range object. It returns a new anonymous Range object. Easiest way to do this is to set the .Name property of the Resized range:
Sub ResizeRange(ByVal RangeName As String, _ Optional NewRowCount As Long = 0, _ Optional NewColumnCount As Long = 0) Dim oRange As Range Set oRange = Range(RangeName) If NewRowCount = 0 Then NewRowCount = oRange.Rows.Count End If If NewColumnCount = 0 Then NewColumnCount = oRange.Columns.Count End If oRange.Resize(NewRowCount, NewColumnCount).Name = RangeName End Sub
Creating a Named Range[edit | edit source]
- Excel 2002
Named Ranges allow the user to refer to a cell or range of cells by name instead of by their cell address. This name can be used in other cell formulas as well as in VBA (e.g. using the [
SomeName]
). There are two sorts of named ranges: Workbook Names and Worksheet Names.
To create a Workbook Name you can select the cell you want to name, pull down Insert—>Name—>Define… This will bring up the «Define Name» dialog. Here you can enter the new name for your cell.
The create a Worksheet Name you follow the same procedure but precede the name with Sheetname!
, e.g. Sheet1!InitialValue
to create a named-range only visible from within worksheet Sheet1
.
When there are two variables with the same name, one local (Worksheet Name) and one global (Workbook Name), the spreadsheet uses the local variable.
There is no way to visualize a named range. The closest thing is to pull down again Insert—>Name—>Define…, but this method does not show if a variable is a local Worksheet Name or a global Workbook Name.
The named range can be a single cell, part of a row, part of a column or a rectangular group of cells. Each one behaves differently:
- A single cell can be referenced anywhere in the worksheet or, if it’s defined globally (workbook name), anywhere in any worksheet.
- A group of cells composing part of a row can only be referenced in a parallel row. For example, if the named variable is mass and it spans the cells C5:L5, then a reference to mass’ at cell E8 (say, a formula like =mass * (3e8)^2) would take the value at C8, but a reference to mass at cell M9 would return an error
- Similarly, a group of cells composing part of a column can only be referenced in a parallel column. Cells outside the range will return an error
- A group of cells that define a rectangular array of sides greater than one is only useful to be referenced in other worksheets — so, there’s no point in defining them locally (worksheet name). For example, if covmatrix are the cells Sheet1!B2:D4, then if cell Sheet2!C3 has the formula =1/sqrt(covmatrix), then it will return 1/sqrt(Sheet1!C3).
Reading a File[edit | edit source]
Reading a file line by line AKA for each line of a file:
MyFileName = "C:UsersJoeDesktopFile.txt" FileNo = FreeFile() Open MyFileName For Input As #FileNo While Not EOF(FileNo) Line Input #FileNo, MyLine MsgBox MyLine Wend Close #FileNo
Links:
- Open at Visual Basic for Applications Reference, msdn.microsoft.com
- Close at Visual Basic for Applications Reference, msdn.microsoft.com
- Line Input at Visual Basic for Applications Reference, msdn.microsoft.com
Writing to a File[edit | edit source]
Writing to a file:
MyFileName = "C:UsersJoeDesktopFile.txt" FileNo = FreeFile() Open MyFileName For Output As #FileNo For I = 1 To 10 Print #FileNo, Str(I); ' The semicolon above prevents printing of a newline Next Close #FileNo
Writing the tab-separated content of the current worksheet to a text file, disregarding some of cell content formatting such as percentages:
MyFileName = "C:UsersJoeDesktopFile.txt" FileNo = FreeFile() Open MyFileName For Output As #FileNo RowCount = ActiveSheet.UsedRange.Cells.Rows.Count ColumnCount = ActiveSheet.UsedRange.Cells.Columns.Count For RowNo = 1 To RowCount For ColNo = 1 To ColumnCount Print #FileNo, Cells(RowNo, ColNo); ' The semicolon bars newline printing If ColNo < ColumnCount Then Print #FileNo, vbTab; End If Next If RowNo < RowCount Then Print #FileNo, vbNewline; End If Next Close #FileNo
Links:
- Open at Visual Basic for Applications Reference, msdn.microsoft.com
- Close at Visual Basic for Applications Reference, msdn.microsoft.com
- Print # at Visual Basic for Applications Reference, msdn.microsoft.com
File Existence[edit | edit source]
Testing whether a file exists:
If Dir(MyFileName) <> "" Then MsgBox "The file exists." End If
Directories[edit | edit source]
Making a directory:
MkDir "C:UsersJoeDesktopTestFolder"
Removing a directory:
RmDir "C:UsersJoeDesktopTestFolder"
Changing to a directory:
Changing the current drive:
Listing the content of a directory, using a custom filter encompassing two file extensions:
Directory = "C:UsersJoe Hoe" Set Files = New Collection Set FileFullPaths = New Collection MyFile = Dir(Directory) While MyFile <> "" Extension = LCase(Right(MyFile, 4)) If Extension = ".txt" Or Extension = ".bat" Then Files.Add MyFile FileFullPaths.Add Directory & MyFile End If MyFile = Dir() 'Next file or folder Wend
Links:
- ChDir at Visual Basic for Applications Reference, msdn.microsoft.com
- ChDrive at Visual Basic for Applications Reference, msdn.microsoft.com
- Dir at Visual Basic for Applications Reference, msdn.microsoft.com
- MkDir at Visual Basic for Applications Reference, msdn.microsoft.com
- RmDir at Visual Basic for Applications Reference, msdn.microsoft.com
Grep[edit | edit source]
Searching for a regular expression in the lines of the files of a directory aka grepping:
Directory = "C:UsersJoe Hoe" PatternString = "target.*path" MyFile = Dir(Directory) Set Lines = New Collection Set RegExp = CreateObject("VBScript.RegExp") RegExp.Pattern = PatternString RegExp.IgnoreCase = True While MyFile <> "" Extension = LCase(Right(MyFile, 4)) If Extension = ".txt" Or Extension = ".bat" Then MyFullFileName = Directory & MyFile FileNo = FreeFile() Open MyFullFileName For Input As #FileNo While Not EOF(FileNo) Line Input #FileNo, MyLine If RegExp.Test(MyLine) Then Lines.Add MyLine End If Wend Close #FileNo End If MyFile = Dir() 'Next file or folder Wend 'Lines is a collection of the matching lines
Clipboard[edit | edit source]
Prerequisites: Accessing the clipboard from an Excel sheet requires that a reference to MSForms (Microsoft Forms Object Library) is set in the sheet. You can set the reference by adding and subsequent removing of a user form, via Insert > UserForm in a pop-up menu. To check the presence of a reference, see Tools > References menu.
Placing text on the clipboard:
Set MyClipboard = New MSForms.DataObject MyClipboard.SetText "My string" MyClipboard.PutInClipboard
Getting text from the clipboard:
Set MyClipboard = New MSForms.DataObject MyClipboard.GetFromClipboard TextContent = MyClipboard.GetText
Links:
- DataObject Class at msdn.microsoft.com; contains a section on Visual Basic, whose applicability to Excel VBA is unclear
Range[edit | edit source]
A range is a set of cells. The cells in a range do not need to be adjacent. However, the cells in a single range do need to belong to a single worksheet.
Defining a new range:
Set MyRange = Selection 'The current selection, possibly of multiple cells Set MyRange = ActiveCell 'The single active cell Set MyRange = Cells(1, 2) 'Row=1, Column=2 AKA B Set MyRange = Cells(1, 1).Offset(0, 1) '=Cells(1, 2) Set MyRange = Cells(1, 2).Offset(0, -1) '=Cells(1, 1) Set MyRange = Cells(1, 1).Offset(0, -1) 'An error Set MyRange = Range("A1:C2") 'Letters indicate columns; numbers indicate rows Set MyRange = Range("A1:A3,C1:C3") 'A discontinuous range Set MyRange = Range("B2:C2").Cells(1, 1) '=Cells(2, 2) =Range("B2") Set MyRange = Rows(1) 'An entire row Set MyRange = Columns(1) 'An entire column Set MyRange = Cells(2,2).EntireRow Set MyRange = Cells(2,2).EntireColumn Set MyRange = Range("B1:C1").EntireColumn 'Two entire columns Set MyRange = Range("B2:D4").End(xlUp) '=Cells(1, 2) =Range("B1") Set MyRange = Range("B2:D4").End(xlToLeft) '=Cells(2, 1) = Range("A2") Set MyRange = Range("B2:D4").End(xlDown) '=Cells(<last row number>, 2) Set MyRange = Range("B2:D4").End(xlToRight) '=Cells(2, <last column number>)
Iterating a range AKA for each cell in a range:
Set MyRange = Selection For Each Cell in MyRange MsgBox Cell Next
Iterating rows and iterating columns AKA for each row of a range and for each column of a range, even if discontiguous:
Set Rng = Range("A1:B1,D3:E3") 'Discontiguous range For Each Row In Rng.Rows RowNo = Row.Row Next For Each Column In Rng.Columns ColNo = Column.Column Next
Making an union (a range subsuming both) or intersection (a range covering only cells in common) of two ranges:
Set MyRange = Range("A1:C2") Set MyRange = Union(MyRange, Range("A5:C5")) MyRange.Interior.Color = RGB(230, 230, 0) Set MyRange = Intersect(MyRange, Columns(2)) MyRange.Interior.Color = RGB(230, 100, 0)
Selecting a range:
Set MyRange = Sheets(1).Range("A1:B1,D1:E1") MyRange.Select 'Even a discontinuous range can be selected
Activating a cell:
Range("A1:B2").Select 'Affects Selection, generally of multiple cells Range("A2").Activate 'Affects ActiveCell, the single one
Finding out about a range AKA learning about a range, including the number of cells AKA cell count, the first row, the last row, the first column, the last column, row count, and column count:
Set Rng = Range("B2:D4") 'Contiguous range NumberOfCells = Rng.Cells.Count FirstRowNo = Rng.Row LastRowNo = Rng.Row + Rng.Rows.Count - 1 'Only for contiguous ranges FirstColNo = Rng.Column LastColNo = Rng.Column + Rng.Columns.Count - 1 'Only for contiguous ranges Set Rng = Range("A1:B1,D1:E1") 'Discontiguous range BrokenLastColNo = Rng.Column + Rng.Columns.Count - 1 'Only for contiguous ranges 'Do it the correct way for discontiguous range LastColNo = 0 For Each Cell in Rng If Cell.Column > LastColNo then LastColNo = Cell.Column End If Next Set RangeWorksheet = Rng.Worksheet
Links:
- Range Collection at Excel 2003 VBA Language Reference at msdn
- Referring to Multiple Ranges at Excel 2003 VBA Language Reference at msdn
- End Property at Excel 2003 VBA Language Reference at msdn
- Intersect Method at Excel 2003 VBA Language Reference at msdn
- Union Method at Excel 2003 VBA Language Reference at msdn
Worksheet[edit | edit source]
To create, access, or delete worksheets, you can use the methods of Worksheet objects. Examples follow.
Set MyNewWorksheet = Sheets.Add 'Create Set MyNewWorksheet2 = Sheets.Add(After:=Sheets(Sheets.Count)) 'Create and place as the last sheet MyNewWorksheet.Name = "My Sheet" Set IndexedWorksheet = Sheets(1) 'Access by index Set NamedWorksheet = Sheets("Name") 'Access by name Set NamedWorksheet2 = Worksheets("Name") 'Does the same thing as the line above MyNewWorksheet.Delete Sheets("Name").Cells(1,1) = "New Value" 'Access the cells of the worksheet Sheets("Name").Cells.Clear 'Clear an entire worksheet, including formatting and cell values Sheets("Name").Columns(1).Sort key1:=Sheets("Name").Range("A1") 'Sort the first column Sheets("Name").Columns(1).Sort key1:=Sheets("Name").Range("A1"), _ order1:=xlDescending, header:=xlYes 'Use descending instead of ascending; do not sort ' the first cell, considering it a header MyNewWorksheet2.Visible = xlSheetHidden MyNewWorksheet2.Visible = xlSheetVisible
Obtaining an existing sheet by name or creating it if it does not exist:
NewSheetName = "My Sheet" Set MySheet = Nothing On Error Resume Next Set MySheet = Sheets(NewSheetName) On Error GoTo 0 If MySheet Is Nothing Then Set MySheet = Sheets.Add(After:=Sheets(Sheets.Count)) MySheet.Name = NewSheetName End If
Links:
- Worksheet Object at Excel 2003 VBA Language Reference at mdsn
- Sheets Collection Object at Excel 2003 VBA Language Reference at mdsn
Searching[edit | edit source]
You can search for values in a sheet as follows:
Dim SoughtString As String SoughtString = "London" Set ForeignKeySheet = Sheets("CitySize") Set FoundCell = ForeignKeySheet.Columns(1).Find(SoughtString, LookAt:=xlWhole) If Not FoundCell Is Nothing Then 'The value associated with the key is in column 2 CitySize = FoundCell.Offset(0, 1) End If
If you want to have a substring match, drop «LookAt:=xlWhole» or use «LookAt:=xlPart».
Links:
- Find Method (Excel 2003 VBA Language Reference) at msdn
Cell Formatting[edit | edit source]
You can format cells including text color, background color, font properties and border, but also formatting as a number, percent or text from VBA as follows:
Selection.Characters.Font.Color = RGB(0, 0, 255) 'Foreground color AKA text color Selection.Interior.Color = RGB(230, 230, 230) 'Background color Selection.Characters.Font.ColorIndex = xlAutomatic 'Reset foreground color Selection.Interior.Color = xlAutomatic 'Reset background color Selection.Font.Name = "Verdana" 'Font face Selection.Font.Size = 8 'Font size Selection.Font.Bold = True Selection.Font.Italic = True Selection.Font.Underline = True 'Selection.Font.Strikethrough = True Selection.Font.Name = Application.StandardFont 'See also ClearFormats below Selection.Font.Size = Application.StandardFontSize 'See also ClearFormats below 'Selection.Borders.LineStyle = xlLineStyleNone or xlDouble or xlDashDotDot or other Selection.Borders.Weight = xlMedium ' xlHairline, xlThin, xlMedium, or xlThick 'Selection.Borders(xlEdgeBottom).Weight = xlThick ' LineStyle and Weight interact in strange ways. Selection.Borders.Color = RGB(127, 127, 0) 'Will be overridden below; applies to all borders Selection.Borders(xlEdgeBottom).Color = RGB(255, 0, 0) Selection.Borders(xlEdgeTop).Color = RGB(0, 255, 0) Selection.Borders(xlEdgeLeft).Color = RGB(0, 0, 255) Selection.Borders(xlEdgeRight).Color = RGB(0, 127, 127) Selection.Borders(xlInsideHorizontal).Color = &H7FFF00 'A tricky hex matching RGB(0, 255, 127) Selection.Borders(xlInsideVertical).Color = RGB(255, 127, 0) Selection.NumberFormat = "General" Selection.NumberFormat = "00" 'As a number with zero decimal places, showing at least two digits Selection.NumberFormat = "0.000" 'As a number, showing three decimal places and no more Selection.NumberFormat = "0.0%" 'As a percent with one decimal place Selection.NumberFormat = "@" 'As text Selection.NumberFormat = "0.00E+00" 'As a number in scientific notation, 'the string before E formatting the significand Selection.NumberFormat = "m/d/yyyy" 'As a date; whether "/" is shown depends on locale Selection.NumberFormat = "d. mmmm yyyy hh:mm:ss" 'As date, showing the month using a word, 'also showing time Selection.ClearFormats 'Remove formatting, keeping cell content. 'Removes also the formatting set using NumberFormat.
Links:
- Font Object (Excel 2003 VBA Language Reference) at msdn
- Borders Collection (Excel 2003 VBA Language Reference) at msdn
- LineStyle Property (Excel 2003 VBA Language Reference) at msdn
- Weight Property (Excel 2003 VBA Language Reference) at msdn
- NumberFormat Property (Excel 2003 VBA Language Reference) at msdn
Color[edit | edit source]
In Excel VBA, RGB colors are plain numbers rather than objects. Some color examples are listed in #Cell Formatting.
Some examples:
Selection.Characters.Font.Color = RGB(0, 0, 255) 'Foreground color AKA text color Selection.Interior.Color = RGB(230, 230, 230) 'Background color Selection.Characters.Font.ColorIndex = xlAutomatic 'Reset foreground color Selection.Comment.Shape.Fill.ForeColor.RGB = RGB(220, 255, 160) 'The above is the fill color, that is, the background color Selection.Comment.Shape.TextFrame.Characters.Font.ColorIndex = 3 'Red per default 'Selection.Comment.Shape.TextFrame.Characters.Font.Color = RGB(255, 0, 0) 'Does not work in Excel 2007 If False Then ActiveWorkbook.Colors(3) = RGB(200, 0, 0) 'Make the red in the index 5 a bit darker End If
Setting the background color of the cells of the 1st column to the row number color index:
For ColorIndex = 1 to 56 Cells(ColorIndex,1).Interior.ColorIndex = ColorIndex Next
Color index in the default palette:
- 0 — Automatic
- 1 — Black
- 2 — White
- 3 — Red
- 4 — Green
- 5 — Blue
- 6 — Yellow
- 7 — Magenta
- 8 — Cyan
- 9 — Dark red
- 10 — Dark green
- 11 — Dark blue
- … etc., through 56
Finding all cells whose text color approaches green:
TargetColor = RGB(0, 255, 0) Tolerance = 200 'Extract the color components. The extraction is unneeded, but if the target 'color came from the color of a selected cell, it would be needed. TmpColor = TargetColor TargetColorRed = TmpColor Mod 256 TmpColor = TmpColor 256 TargetColorGreen = TmpColor Mod 256 TmpColor = TmpColor 256 TargetColorBlue = TmpColor Mod 256 For Each Cell In ActiveSheet.UsedRange.Cells MyColor = Cell.Characters.Font.Color 'Color is a number 'Extract the RGB components of the color Red = MyColor Mod 256 MyColor = MyColor 256 Green = MyColor Mod 256 MyColor = MyColor 256 Blue = MyColor Mod 256 'Find the distance from the target color Distance = ((Red - TargetColorRed) ^ 2 + _ (Green - TargetColorGreen) ^ 2 + _ (Blue - TargetColorBlue) ^ 2) ^ 0.5 If Distance < Tolerance Then Cell.Interior.Color = RGB(230, 230, 230) 'Mark the cell using its background color End If Next
Links:
- Color Property at Excel 2003 VBA Language Reference at msdn
- ColorIndex Property at Excel 2003 VBA Language Reference at msdn
- Colors Property at Excel 2003 VBA Language Reference at msdn
- ColorType Property at Excel 2003 VBA Language Reference at msdn
- PatternColor Property at Excel 2003 VBA Language Reference at msdn
- PatternColorIndex Property at Excel 2003 VBA Language Reference at msdn
Visibility[edit | edit source]
Hiding a row (hide a row, hide row):
Rows(2).Hidden = True 'Rows(2).Hidden = False 'Show it again
Hiding several rows at once:
Range("A1:A3").EntireRow.Hidden = True 'Hide rows 1, 2, and 3
Hiding the rows of the currently selected cells:
Selection.EntireRow.Hidden = True
Looping over rows that are visible AKA shown AKA not hidden:
For RowNo = 1 To 10 If Not Rows(RowNo).Hidden Then 'Do something on the row End If Next
Toggling the visibility of rows:
For RowNo = 1 To 10 If Not Rows(RowNo).Hidden Then Rows(RowNo).Hidden = True Else Rows(RowNo).Hidden = False End If Next
Hiding a column (hide a column, hide column):
Columns(2).Hidden = True 'Columns(2).Hidden = False 'Show it again
Hiding several columns at once:
Range("A1:C1").EntireColumn.Hidden = True 'Hide columns 1, 2, and 3
Hiding the columns of the currently selected cells:
Selection.EntireColumn.Hidden = True
Other tricks pertaining to visibility of columns work in a direct analogy to the examples for rows above.
Hyperlink[edit | edit source]
Opening or following a hyperlink (open a hyperlink, follow a hyperlink, open hyperlink, follow hyperlink):
ActiveWorkbook.FollowHyperlink "http://www.microsoft.com"
Opening the Wikipedia article for the article title found in the single active cell by opening a put-together URL:
ActiveWorkbook.FollowHyperlink "http://en.wikipedia.org/wiki/" & ActiveCell
Opening a Wikipedia article per article title in any of the currently selected cells:
For Each Cell In Selection ActiveWorkbook.FollowHyperlink "http://en.wikipedia.org/wiki/" & Cell Next
Opening a local hyperlink, with a possible pop-up asking for confirmation for security reasons:
ActiveWorkbook.FollowHyperlink "file://C:UsersJoe HoeDesktopTest.txt"
Links:
- FollowHyperlink Method (Excel 2003 VBA Language Reference) at msdn
Temporary file[edit | edit source]
Getting a temporary file, with unclear robustness of the following method, which uses random numbers and tests for file existence:
Function GetTempFile(Prefix As String, Suffix As String) As String TempFolder = Environ$("tmp") Randomize While True TempFileName = TempFolder & "" & Prefix & CStr(Int(10000000 * Rnd)) & Suffix If Dir(TempFileName) = "" Then 'Then the file does not exist GetTempFile = TempFileName Exit Function End If Wend End Function
Links:
- How To Use GetTempFileName API to Create a Unique Temporary File at Microsoft.com
Command Output[edit | edit source]
If you do not mind a popping up console window, here is a way of obtaining output of a command from Excel VBA:
Set MyShell = CreateObject("WScript.Shell") Set ExecObject = MyShell.Exec("tasklist /v") ' AllText = ExecObject.StdOut.ReadAll Do While Not ExecObject.StdOut.AtEndOfStream Line = ExecObject.StdOut.ReadLine() If InStr(Line, "AcroRd32.exe") > 0 Then 'Do something End If Loop
If having a console window popping up is not acceptable and you are okay with creating a temporary file, here is another way of obtaining output of a command from Excel VBA:
'Summary: Run "attrib" on the file in column A (1) of the row 'of the currently selected cell, writing the result into 'column B (2) of the row. 'Get temp file name TempFolder = Environ$("tmp") Randomize TempFileName = "" While TempFileName = "" TempFileNameCand = TempFolder & "" & "mytmp" & CStr(Int(10000000 * Rnd)) & ".tmp" If Dir(TempFileNameCand) = "" Then 'Then the file does not exist TempFileName = TempFileNameCand End If Wend 'Run the command Set MyShell = CreateObject("WScript.Shell") MyCommand = "cmd /c attrib """ & Cells(Selection.Row, 1) & """ >" & TempFileName MyShell.Run MyCommand, 0, True '0 = show no window 'Although attrib has an exe file, we need to use "cmd" for the 'redirection to work. FileNo = FreeFile() Open TempFileName For Input As #FileNo While Not EOF(FileNo) Line Input #FileNo, MyLine Cells(Selection.Row, 2) = MyLine Wend Close #FileNo Kill TempFileName 'Delete the file to clean up, although not strictly necessary
Using cmd /c, you can run chains of commands connected using & or | as well:
Set MyShell = CreateObject("WScript.Shell") Set ExecObject = MyShell.Exec("cmd /c cd /d C:UsersJoe Hoe & findstr /s knowledge *.txt") ' AllText = ExecObject.StdOut.ReadAll Do While Not ExecObject.StdOut.AtEndOfStream Line = ExecObject.StdOut.ReadLine() 'Do something Loop
Links:
- Capture output value from a shell command in VBA? at stackoverflow
Dimensions[edit | edit source]
Row height and column width:
Selection.RowHeight = 15 Cells(1,1).RowHeight = 15 'Can be applied to cells, not only to rows Rows(4).AutoFit 'Automatically adjust row height 'Cells(4, 1).AutoFit 'Error Cells(4, 1).EntireRow.AutoFit Selection.EntireRow.AutoFit 'Auto fit the row height of the current selection ActiveSheet.UsedRange.Rows.AutoFit 'Auto fit the row height of the entire sheet Selection.RowHeight = ActiveSheet.StandardHeight Columns(1).ColumnWidth = 70 Cells(1,1).ColumnWidth = 70 'Can be applied to cells, not only to columns Columns(2).AutoFit 'Automatically adjust column width Selection.EntireRow.AutoFit 'Auto fit the column width of the current selection ActiveSheet.UsedRange.Columns.AutoFit 'Auto fit the column width of the entire sheet Selection.ColumnWidth = ActiveSheet.StandardWidth
Links:
- RowHeight Property at Excel 2003 VBA Language Reference at msdn
- ColumnWidth Property at Excel 2003 VBA Language Reference at msdn
- StandardHeight Property at Excel 2003 VBA Language Reference at msdn
- StandardWidth Property at Excel 2003 VBA Language Reference at msdn
[edit | edit source]
Working with comment aka note:
If Cells(1,1).Comment Is Nothing Then Cells(1,1).AddComment Text:="Hey" 'AddComment throws an error if the cell already has a comment 'Range("A2:A3").AddComment Text:="Hey" 'Error 'AddComment throws an error if applies to more than one cell at once. End If Cells(1,1).Comment.Text Text:=Selection.Comment.Text & " there" Cells(1,1).Comment.Visible = True 'Prevent the comment from autohiding Cells(1,1).Comment.Visible = False 'The default setting Cells(1,1).Comment.Shape.Fill.ForeColor.RGB = RGB(220, 255, 160) 'The above is the fill color, that is, the background color Cells(1,1).Comment.Shape.Height = 60 Cells(1,1).Comment.Shape.Width = 80 Cells(1,1).Comment.Shape.TextFrame.Characters.Font.Name = "Verdana" Cells(1,1).Comment.Shape.TextFrame.Characters.Font.Size = 9 Cells(1,1).Comment.Shape.TextFrame.Characters(1, 3).Font.Bold = True If False Then 'Selection.Comment.Delete Cells(1,1).ClearComments Range("A1:A2").ClearComments 'Can apply to several cells at once Cells(1,1).PasteSpecial Paste:=xlPasteComments End If
Collecting all comments of the sheet into a string:
CommentString = "" For Each Comment in ActiveSheet.Comments CommentString = CommentString & " " & Comment.Text Next
Links:
- Comment Object at Excel 2003 VBA Language Reference at msdn
- Shape Object at Excel 2003 VBA Language Reference at msdn
IsEmpty[edit | edit source]
Approximately speaking, tells whether a variable has been initialized and not yet written to.
Can be used to tell whether a cell is empty; the presence of a comment attached to the cell or formatting of the cell does not make a cell non-empty.
Examples:
Set MyCell = Cells(1, 1) If IsEmpty(MyCell) Then MyCell.Value = "New value" End If ' MyCell.Value = "" Result1 = IsEmpty(MyCell) 'True ' Dim MyVar Result2 = IsEmpty(MyVar) 'True MyVar = "" Result3 = IsEmpty(MyVar) 'False MyVar = Empty Result4 = IsEmpty(MyVar) 'True
Links:
- IsEmpty at Excel 2010 VBA Language Reference at msdn
IsNull[edit | edit source]
Tells whether an expression is Null, which is distinct from Empty.
Null can be assigned to variant variables; it cannot be assigned to variables dimensioned as strings or integers. Null cannot be assigned to objects, unlike Nothing.
Examples:
Result1 = IsNull(Null) 'True Result2 = IsNull(Empty) 'False ' Dim MyVar As Variant MyVar = Null 'All right Result3 = IsNull(MyVar) 'True Dim MyColl As Collection Set MyColl = Nothing 'All right Set MyColl = Null 'Error Dim MyStr As String MyStr = Null 'Error Dim MyInt As Integer MyInt = Null 'Error
Links:
- IsNull at Excel 2013 VBA Language Reference at msdn
Add-Ins at Startup[edit | edit source]
Controlling what add-ins Excel opens at startup:
Microsoft Excel 2003: Configure loaded add-ins via Tools -> Add-ins. Their list is mirrored in the following Registry key, but there’s no advantage in editing the Registry:
HKCUSoftwareMicrosoftOffice11.0ExcelInit Commands
Microsoft Excel 2002 SP-2:When you start Excel, it may automatically load addins (i.e. those you added from Tools -> Add-Ins). The list of add-ins that get loaded come from the following registry key:
HKCUSoftwareMicrosoftOffice10.0ExcelOptions
Under this key you may find a list of string-variables:
- OPEN
- OPEN1
- OPEN2
- etc…
The values of these variables is the name of the add-in. Excel, on start-up, will attempt to load the add-in in string-variable OPEN first, then OPEN1 (if present), onward until it runs out of such string-variables. It seems like Excel will automatically renumber the keys if they are not consecutive (i.e. OPEN1, OPEN3, OPEN4 will become OPEN1, OPEN2, OPEN3).
Note also the list of add-ins presented when you do Tools -> Add-Ons is, in part, populated by the contents of the following key:
HKCUSoftwareMicrosoftOffice10.0ExcelAddin Manager
See also the following MS KB article: How to Remove Entries from Add-Ins Dialog Box.
Chart direct from VBA array data[edit | edit source]
Charts need not be based on the values in cells of a spreadsheet, but can also be made directly in VBA from an array. The following code makes a chart of the relative frequency of characters in a string, in percent of the total, or normalized to a maximum of unity. There is also an option to sort the display and the content can be changed by modifying the content or sequence of the vRef array. Procedures to remove charts and test the functions are included.
Sub TestChartOfStrFreq() 'run this to make a chart Dim str As String, n As Long, c As Long 'place user string here str = "" 'if no user string use these random charas If str = "" Then Do DoEvents Randomize n = Int((127 - 0 + 1) * Rnd + 0) Select Case n 'numbers, and upper and lower letters Case 48 To 57, 65 To 90, 97 To 122 str = str & Chr(n) c = c + 1 End Select Loop Until c = 1000 End If If ChartOfStrFreq(str, 1, 1) Then MsgBox "Chart done..." End Sub Sub DeleteAllWorkbookCharts5() 'run this to delete all charts Dim oC Application.DisplayAlerts = False For Each oC In ThisWorkbook.Charts oC.Delete Next oC Application.DisplayAlerts = True End Sub Function ChartOfStrFreq(sIn As String, Optional bSort As Boolean = False, Optional bNormalize As Boolean = False) As Boolean 'makes Excel bar-graph chart for percentage incidence of vRef charas in string (or normalized to max value= 1) 'bSort = True for descending percent otherwise vRef sequence 'PREP Dim vRef As Variant, LBC As Long, UBC As Long, LBR As Long, UBR As Long Dim vW() As Variant, x() As Variant, y() As Variant Dim sUC As String, nC As Long, n As Long, sS As String, nS As Long Dim vR As Variant, bCond As Boolean, SortIndex As Long, temp As Variant Dim t As Variant, i As Long, j As Long, q As Long, max As Variant Dim bXValueLabels As Boolean, sT As String, sX As String, sY As String If sIn = "" Then MsgBox "Empty input string - closing" Exit Function End If 'load the intended x-axis display set here...add to it and delete as required vRef = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", _ "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", _ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9") 'set axis labels etc... sT = "Selective Distribution from a " & Len(sIn) & "-Character String" sX = "Character Set of Interest" If bNormalize Then sY = "Count Divided by Maximum Value" Else sY = "Percentage of Original String" End If bXValueLabels = True LBC = LBound(vRef): UBC = UBound(vRef) ReDim vW(0 To 2, LBC To UBC) LBR = LBound(vW, 1): UBR = UBound(vW, 1) ReDim x(LBC To UBC) ReDim y(LBC To UBC) 'COUNT sUC = UCase(sIn) nC = Len(sIn) For n = LBC To UBC vW(0, n) = vRef(n) 'all charas to first row sS = vW(0, n) 'count hits in string for each chara in ref set vW(1, n) = UBound(Split(sUC, sS)) - LBound(Split(sUC, sS)) 'count hits 'calculate hits as percentages of total chara count vW(2, n) = Round(((vW(1, n)) * 100 / nC), 2) Next n 'NORMALIZE If bNormalize Then max = vW(1, FindMax(vW, 1)) For n = LBC To UBC temp = vW(1, n) vW(2, n) = Round((temp / max), 2) Next n End If 'SORT If bSort Then SortIndex = 2 'descending sort, on rows For i = LBC To UBC - 1 For j = LBC To UBC - 1 bCond = vW(SortIndex, j) < vW(SortIndex, j + 1) If bCond Then For q = LBR To UBR t = vW(q, j) vW(q, j) = vW(q, j + 1) vW(q, j + 1) = t Next q End If Next Next End If 'CHART 'transfer data to chart arrays For n = LBC To UBC x(n) = vW(0, n) 'x axis data y(n) = vW(2, n) 'y axis data Next n 'make chart Charts.Add ActiveChart.ChartType = xlColumnClustered 'column chart 'assign the data and labels to a series With ActiveChart.SeriesCollection If .count = 0 Then .NewSeries If bXValueLabels Then .Item(1).ApplyDataLabels Type:=xlDataLabelsShowValue .Item(1).DataLabels.Orientation = 60 End If If Val(Application.Version) >= 12 Then .Item(1).Values = y .Item(1).XValues = x Else .Item(1).Select Names.Add "_", x ExecuteExcel4Macro "series.x(!_)" Names.Add "_", y ExecuteExcel4Macro "series.y(,!_)" Names("_").Delete End If End With 'apply title string, x and y axis strings, and delete legend With ActiveChart .HasTitle = True .ChartTitle.Text = sT .SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis) 'X .Axes(xlCategory).AxisTitle.Text = sX .SetElement (msoElementPrimaryValueAxisTitleRotated) 'Y .Axes(xlValue).AxisTitle.Text = sY .Legend.Delete End With ActiveChart.ChartArea.Select ChartOfStrFreq = True End Function Public Function FindMax(arr() As Variant, row As Long) As Long Dim myMax As Long Dim i As Long For i = LBound(arr, 2) To UBound(arr, 2) If arr(row, i) > myMax Then myMax = arr(row, i) FindMax = i End If Next i End Function
Nuking Retained State[edit | edit source]
- Works on: Microsoft Excel 2002 SP-2
- OS: Windows XP
Nuking Excel’s Retained State: Excel remembers all sorts of things between runs: What addins to load, what buttons and menus to display, etc. Sometime you’ll want to clean all of this stuff up and bring Excel back to its factory state.
Nuking Excel Checklist:
- Make sure the following directories are empty:
- C:Program FilesMicrosoft OfficeOffice10xlstart
- C:appsxpapplication dataMicrosoftxlstart
- Nuke the auto-open keys from the registry(as shown below);
- Nuke all .xlbs – For example check here:
- C:appsxpapplication dataMicrosoftExcel
[edit | edit source]
- Visual Basic
External links[edit | edit source]
- The Mr. Excel Forum: This is a great super-active forum where Excel power-users can often be found.
- Woody’s Lounge
- J Rubin’s ExcelTip.com
- OzGrid
- Express
- Chip Pearson
- Ron de Bruin
- BygSoftware.com: This site has loads of practical examples showing Excel’s potential
- Aspose.Cells for .NET/Java : A component available for .NET and Java that can be used by developers to create and manipulate Excel files without the need for MS Office to be installed on the system.
In This Chapter
Gaining a conceptual overview of VBA Finding out what you can do with VBA
Discovering the advantages and disadvantages of using VBA Taking a mini-lesson on the history of Excel
This chapter is completely devoid of any hands-on training material. It does, however, contain some essential background information that assists you in becoming an Excel programmer. In other words, this chapter paves the way for everything else that follows and gives you a feel for how Excel programming fits into the overall scheme of the universe.
Okay, So What Is VBA?
VBA, which stands for Visual Basic for Applications, is a programming language developed by Microsoft — you know, the company run by the richest man in the world. Excel, along with the other members of Microsoft Office 2003, includes the VBA language (at no extra charge). In a nutshell, VBA is the tool that people like you and me use to develop programs that control Excel.
Don’t confuse VBA with VB (which stands for Visual Basic). VB is a programming language that lets you create standalone executable programs (those EXE files). Although VBA and VB have a lot in common, they are different animals.
A few words about terminology
Excel programming terminology can be a bit confusing. For example, VBA is a programming language, but it also serves as a macro language. What do you call something written in VBA and executed in Excel? Is it a macro or is it a program? Excel’s Help system often refers to VBA procedures as macros, so I use that terminology. But I also call this stuff a program.
I use the term automate throughout this topic. This term means that a series of steps is completed automatically. For example, if you write a macro that adds color to some cells, prints the worksheet, and then removes the color, you have automated those three steps.
By the way, macro does not stand for Messy And Confusing Repeated Operation. Rather, it comes from the Greek makros, which means large — which also describes your paycheck after you become an expert macro programmer.
What Can You Do With VBA?
You’re probably aware that people use Excel for thousands of different tasks. Here are just a few examples:
Keeping lists of things such as customer names, students’ grades, or holiday gift ideas
Budgeting and forecasting
Analyzing scientific data
Creating invoices and other forms
Developing charts from data
Yadda, yadda, yadda
The list could go on and on, but I think you get the idea. My point is simply that Excel is used for a wide variety of things, and everyone reading this topic has different needs and expectations regarding Excel. One thing virtually every reader has in common is the need to automate some aspect of Excel. That, dear reader, is what VBA is all about.
For example, you might create a VBA program to format and print your month-end sales report. After developing and testing the program, you can execute the macro with a single command, causing Excel to automatically perform many time-consuming procedures. Rather than struggle through a tedious sequence of commands, you can grab a cup of joe and let your computer do the work — which is how it’s supposed to be, right?
In the following sections, I briefly describe some common uses for VBA macros. One or two of these may push your button.
Inserting a text string
If you often need to enter your company name into worksheets, you can create a macro to do the typing for you. You can extend this concept as far as you like. For example, you might develop a macro that automatically types a list of all salespeople who work for your company.
Automating a task you perform frequently
Assume you’re a sales manager and need to prepare a month-end sales report to keep your boss happy. If the task is straightforward, you can develop a VBA program to do it for you. Your boss will be impressed by the consistently high quality of your reports, and you’ll be promoted to a new job for which you are highly unqualified.
Automating repetitive operations
If you need to perform the same action on, say, 12 different Excel workbooks, you can record a macro while you perform the task on the first workbook and then let the macro repeat your action on the other workbooks. The nice thing about this is that Excel never complains about being bored. Excel’s macro recorder is similar to recording sound on a tape recorder. But it doesn’t require a microphone.
Creating a custom command
Do you often issue the same sequence of Excel menu commands? If so, save yourself a few seconds by developing a macro that combines these commands into a single custom command, which you can execute with a single keystroke or button click.
Creating a custom toolbar button
You can customize the Excel toolbars with your own buttons that execute the macros you write. Office workers tend to be very impressed by this sort of thing.
Creating a custom menu command
You can also customize Excel’s menus with your own commands that execute macros you write. Office workers are even more impressed by this.
Creating a simplified front end
In almost any office, you can find lots of people who don’t really understand how to use computers. (Sound familiar?) Using VBA, you can make it easy for these inexperienced users to perform some useful work. For example, you can set up a foolproof data-entry template so you don’t have to waste your time doing mundane work.
Developing new worksheet functions
Although Excel includes numerous built-in functions (such as SUM and AVERAGE), you can create custom worksheet functions that can greatly simplify your formulas. I guarantee you’ll be surprised by how easy this is. (I show you how to do this in Chapter 21.) Even better, the Insert Function dialog box displays your custom functions, making them appear built in. Very snazzy stuff.
Creating complete, macro-driven applications
If you’re willing to spend some time, you can use VBA to create large-scale applications complete with custom dialog boxes, onscreen help, and lots of other accoutrements.
Creating custom add-ins for Excel
You’re probably familiar with some of the add-ins that ship with Excel. For example, the Analysis ToolPak is a popular add-in. You can use VBA to develop your own special-purpose add-ins. I developed my Power Utility Pak add-in using only VBA.
Advantages and Disadvantages of VBA
In this section I briefly describe the good things about VBA — and I also explore its darker side.
VBA advantages
You can automate almost anything you do in Excel. To do so, you write instructions that Excel carries out. Automating a task by using VBA offers several advantages:
Excel always executes the task in exactly the same way. (In most cases, consistency is a good thing.)
Excel performs the task much faster than you could do it manually (unless, of course, you’re Clark Kent).
If you’re a good macro programmer, Excel always performs the task without errors (which probably can’t be said about you or me).
The task can be performed by someone who doesn’t know anything about Excel.
You can do things in Excel that are otherwise impossible — which can make you a very popular person around the office.
For long, time-consuming tasks, you don’t have to sit in front of your computer and get bored. Excel does the work, while you hang out at the water cooler.
VBA disadvantages
It’s only fair that I give equal time to listing the disadvantages (or potential disadvantages) of VBA:
You have to learn how to write programs in VBA (but that’s why you bought this topic, right?). Fortunately, it’s not as difficult as you might expect.
Other people who need to use your VBA programs must have their own copies of Excel. It would be nice if you could press a button that transforms your Excel/VBA application into a stand-alone program, but that isn’t possible (and probably never will be).
A personal anecdote
Excel programming has its own challenges and frustrations. One of my earlier topics, Excel 5 For Windows Power Programming Techniques, included a disk containing the examples from the topic. I compressed these files so that they would fit on a single disk. Trying to be clever, I wrote a VBA program to expand the files and copy them to the appropriate directories. I spent a lot of time writing and debugging the code, and I tested it thoroughly on three different computers.
Imagine my surprise when I started receiving e-mail from readers who could not install the files. With a bit of sleuthing, I eventually discovered that the readers who were having the problem had all upgraded to Excel 5.0c. (I developed my installation program using Excel 5.0a.) It turns out that the Excel 5.0c upgrade featured a very subtle change that caused my macro to bomb. Because I’m not privy to Microsoft’s plans, I didn’t anticipate this problem. Needless to say, this author suffered lots of embarrassment and had to e-mail corrections to hundreds of frustrated readers.
Sometimes, things go wrong. In other words, you can’t blindly assume that your VBA program will always work correctly under all circumstances. Welcome to the world of debugging.
VBA is a moving target. As you know, Microsoft is continually upgrading Excel. You may discover that VBA code you’ve written doesn’t work properly with a future version of Excel. Take it from me; I discovered this the hard way, as detailed in the “A personal anecdote” sidebar.
VBA in a Nutshell
A quick and dirty summary follows of what VBA is all about. Of course, I describe all this stuff in semiexcruciating detail later in the topic.
You perform actions in VBA by writing (or recording) code in a VBA module. You view and edit VBA modules using the Visual Basic Editor (VBE).
A VBA module consists of Sub procedures. A Sub procedure has nothing to do with underwater vessels or tasty sandwiches. Rather, it’s computer code that performs some action on or with objects (discussed in a moment). The following example shows a simple Sub procedure called Test. This amazing program displays the result of 1 plus 1.
A VBA module can also have Function procedures. A Function procedure returns a single value. You can call it from another VBA procedure or even use it as a function in a worksheet formula. An example of a Function procedure (named Add Two) follows. This Function accepts two numbers (called arguments) and returns the sum of those values.
VBA manipulates objects. Excel provides more than 100 objects that you can manipulate. Examples of objects include a workbook, a worksheet, a cell range, a chart, and a shape. You have many, many more objects at your disposal, and you can manipulate them using VBA code.
Objects are arranged in a hierarchy. Objects can act as containers for other objects. At the top of the object hierarchy is Excel. Excel itself is an object called Application, and it contains other objects such as Workbook objects and Command Bar objects. The Workbook object can contain other objects, such as Worksheet objects and Chart objects. A Worksheet object can contain objects such as Range objects and PivotTable objects. The term object model refers to the arrangement of these objects. (See Chapter 4 for details.)
Objects of the same type form a collection. For example, the Worksheets collection consists of all the worksheets in a particular workbook. The Charts collection consists of all Chart objects in a workbook. Collections are themselves objects.
You refer to an object by specifying its position in the object hierarchy, using a dot as a separator. For example, you can refer to the workbook Topic1.xls as
This refers to the workbook Topic1.xls in the Workbooks collection. The Workbooks collection is contained in the Application object (that is, Excel). Extending this to another level, you can refer to Sheet1 in Topic1.xls as
As shown in the following example, you can take this to still another level and refer to a specific cell (in this case, cell A1):
‘ If you omit specific references, Excel uses the active objects. If Topic 1. xls is the active workbook, you can simplify the preceding reference as follows:
If you know that Sheet1 is the active sheet, you can simplify the reference even more:
Objects have properties. You can think of a property as a setting for an object. For example, a Range object has such properties as Value and Address. A Chart object has such properties as HasTitle and Type. You can use VBA to determine object properties and to change properties.
You refer to a property of an object by combining the object name with the property name, separated by a period. For example, you can refer to the value in cell A1 on Sheet1 as follows:
You can assign values to variables. A variable is a named element that stores things. You can use variables in your VBA code to store such things as values, text, or property settings. To assign the value in cell A1 on Sheet1 to a variable called Interest, use the following VBA statement:
Objects have methods. A method is an action Excel performs with an object. For example, one of the methods for a Range object is Clear Contents. This method clears the contents of the range.
You specify a method by combining the object with the method, separated by a dot. For example, the following statement clears the contents of cell A1:
VBA includes all the constructs of modern programming languages, including arrays and looping.
Believe it or not, the preceding list pretty much describes VBA in a nutshell. Now you just have to find out the details. That’s the purpose of the rest of this topic.
An Excursion into Versions
If you plan to develop VBA macros, you should have some understanding of Excel’s history. I know you weren’t expecting a history lesson, but this is important stuff.
Here are all the major Excel for Windows versions that have seen the light of day, along with a few words about how they handle macros:
Excel 2: The original version of Excel for Windows was called Version 2 (rather than 1) so that it would correspond to the Macintosh version. Excel 2 first appeared in 1987 and nobody uses it anymore, so you can pretty much forget that it ever existed.
Excel 3: Released in late 1990, this version features the XLM macro language. A few people live in a time warp and still use this version.
Excel 4: This version hit the streets in early 1992. It also uses the XLM macro language. A fair number of people still use this version. (They subscribe to the philosophy if it ain’t broke, don’t fix it.)
Excel 5: This one came out in early 1994. It was the first version to use VBA (but it also supports XLM). Many people continue to use this version because they are reluctant to move up to Windows 95.
Excel 95: Technically known as Excel 7 (there is no Excel 6), this version began shipping in the summer of 1995. It’s a 32-bit version and requires Windows 95 or Windows NT. It has a few VBA enhancements, and it supports the XLM language. Excel 95 uses the same file format as Excel 5.
Excel 97: This version (also known as Excel was born in January 1997. It requires Windows 95 or Windows NT. It has many enhancements and features an entirely new interface for programming VBA macros. Excel 97 also uses a new file format (which previous Excel versions cannot open).
Excel 2000: This version’s numbering scheme jumped to four digits. Excel 2000 (also known as Excel 9) made its public debut in June 1999. It includes only a few enhancements from a programmer’s perspective, with most enhancements being for users — particularly online users.
Excel 2002: This version (also known as Excel 10 or Excel XP) appeared in late 2001. Perhaps this version’s most significant feature is the ability to recover your work when Excel crashes. This is also the first version to use copy protection (known as product activation).
Excel 2003: As I write this topic, this is the current version and it is also known as Excel 11. Of all the Excel upgrades I’ve ever seen (and I’ve seen them all), Excel 2003 has the fewest new features. In other words, most hard-core Excel users (including yours truly) were very disappointed with Excel 2003.
So what’s the point of this mini history lesson? If you plan to distribute your Excel/VBA files to other users, it’s vitally important that you understand which version of Excel they use. People using an older version won’t be able to take advantage of features introduced in later versions. For example, VBA’s Split function was introduced in Excel 2000. If your VBA code uses this function, those running an earlier version of Excel will have problems. Specifically, they will see a “compile error” message, and nothing executes.
Visual Basic for Applications, better known as Excel VBA, is a programming language used in many Microsoft apps. A VBA application can automate your business procedures. It allows you to access the information, irrespective of your physical location. In addition to consolidating your data in the cloud, VBA has several other benefits. However, Microsoft Excel VBA programming is not everyone’s cup of tea. Enrolling for an MS Excel VBA tutorial will teach you the business benefits of VBA. You will learn how applications like data-entry spreadsheets that can generate reports and how Excel VBA can improve your entire management tracking system. Learn Excel 2003 VBA tutorial to know the basics of VB programming.
Excel VBA Tutorial will also give you insights on the endless opportunities to build efficient business processes to do more with the data. Signing up for a VBA tutorial Excel 2016 will help you learn the new features in Excel and also improve productivity at work. Here I have explored Excel VBA in details and what an Excel VBA Tutorial can do for your career.
What is Excel VBA?
Excel VBA stands for Visual Basic for Applications. VBA is a combination of Microsoft’s event-driven programming language Visual Basic with Microsoft Office applications such as Microsoft Excel. It enables you to automate various activities in Excel, such as generating reports, preparing charts & graphs, calculations, etc.
Let us explore some well-known Excel VBA features:
MS Excel VBA Features
Macro: Macro is one of the most useful features in Excel 2003 VBA and Excel 2016 VBA. Most MS Excel VBA tutorials include a separate section on Macros. Macros in Excel VBA allow you to automate tasks in Excel by writing.
Macros allow users to automatically generate customized charts, reports and perform other data processing functions. In addition, Macros automate tasks and merge program functions that enable developers to build custom solutions using Visual Basic. Visual Basic for Applications requires code to run within a host application such as Excel because it cannot run as a stand-alone application.
CHOOSE function:
The Microsoft Excel CHOOSE function another important module in Excel VBA Tutorial returns a value from a list of values based on a given position. The CHOOSE function is a built-in function in Excel that is categorized as a Lookup/Reference Function. It can be used as a worksheet function (WS) and a VBA function (VBA) in Excel. As a worksheet function, the CHOOSE function can be entered as part of a formula in a cell of a worksheet. As a VBA function, you can also use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Workbook and Worksheet Object: In Excel VBA, an object can contain another object, and that object can contain another object. In other words, Excel VBA programming involves working with an object hierarchy. The Worksheet object is a member of the Worksheets collection. The Worksheets collection contains all the Worksheet objects in a workbook. The Worksheet object is also a member of the Sheets collection. The Sheets collection contains all the sheets in the workbook (both chart sheets and worksheets).
Range Object: In Microsoft Excel VBA, a range is a collection of cells. A range can be 2 or more cells and those cells don’t necessarily have to be adjacent to each other. The Range object, which is the representation of a cell (or cells) on your worksheet, is the most important object of Excel VBA. There are many things that you can do with ranges in Excel such as copying, moving, formatting, and naming ranges. Here is a list of topics that explain how to use ranges in Excel.
Collections: Many VBA excel functions objects come in both singular and plural forms—Workbook and Workbooks, Worksheet and Worksheets, and more. The plural varieties are called collections. Collection objects are used to do an action on numerous items in the collection. This function, which is included in Excel VBA Tutorial courses, is used:
- Generating a list of employees’ data
- Generating a list of students’ grades
- Formal working report
- Generating charts from databases
- Generating forms and invoices
- Budgeting and evaluating scientific data
Loop: Looping is one of the most powerful programming techniques in MS Excel VBA. It is usually covered in most MS Excel VBA tutorials. If you want to perform the same task multiple times VBA Loops can be used. The VBA Loop types can be of three types:
- For Loop
- Do While Loop
- Do Until Loop
A loop in Excel VBA enables you to loop through a range of cells with just a few codes lines. The Visual Basic ‘For’ loop takes on two separate forms. These are the For … Next loop and the For Each loop.
- The For … Next Loop:
The For … Next loop uses a variable, which cycles through a series of values within a specified range. The VBA code inside the loop is then executed for each value.
- The For Each Loop:
The For Each loop is similar to the For … Next loop but, instead of running through a set of values for a variable, the For Each loop runs through every object within a set of objects.
Array:
Excel Visual Basic arrays are structures which are used to store a set of related variables of the same type. Each of the entries in the array can be accessed by an index number. Arrays can be one-dimensional, multi-dimensional, and dynamic. Arrays are part of all MS Excel VBA tutorials
String Manipulation: The Microsoft Excel STR function, one of the popular functions of Excel VBA, returns a string representation of a number. The STR function is a built-in function in Excel that is categorized as a String/Text Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Date and Time: The Microsoft Excel DATE function returns the current system date. The DATE function is a built-in function in Excel that is categorized as a Date/Time Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Properties and Methods: You can operate objects by setting their Properties and calling their Approaches. Setting a property alters some superiority of the object. Calling a method causes the object to complete some action. For example, the Workbook object has a Close method that ends the workbook and an Active Sheet property that signifies the sheet that is presently active in the workbook.
PivotTables: PivotTables allow you to transform and analyze data in a structured manner. Just select a range of data (data in columns with headers) and select the ROWS, COLUMNS, and VALUES for your Pivot Table! You can also create custom columns (based on formulas), summarize data by groups/rows/columns etc. There is almost no limit to the possibilities.
Filtering and Sorting Data: Filtering and sorting your data is just as useful as using PivotTables. Excel is meant to transform and analyze data and filtering/sorting is one of the key elements. When provided with a table of data you will probably want to sort the data in a descending/ascending manner or filter out rows based on some features (values in certain columns). This is a must-know feature.
Conditional Formatting: Analyzing/transforming data is important, but it is just as useful to be able to identify variances in a range of values using graphics like colors, bars or icons. Conditional formatting can allow you to notice patterns in data values which might not be obvious when looking at raw numbers.
Microsoft Power Add-Ins:
Microsoft Power Add-Ins are one of the more commonly used Excel features, that include PowerPivot, PowerQuery and PowerMap powerful Microsoft developed Add-Ins for Excel. Harness the power of Big Data, SQL, complex pivots and charts with these fantastic Add-ins! The PowerMap is a relatively new member of the family delivering nice bells and whistles to your Workbooks!
PowerPivot enriches Excel with more Analytics features by extending the PivotTable with summarization, cross-tabulation, expanded data capacity, advanced calculations, ability to import data from multiple sources, and the ability to publish the workbooks as interactive web applications.
PowerQuery allows you to easily harness data and access to external data sources such as files, the Web, databases etc. and more easily manipulate and cleanse data. PowerQuery enables you to process enormous data sources/tables counting millions of records (more than an Excel Worksheet can contain).
Want to learn much more about VBA programming in Excel? You can find related examples and features on Excel 2003 VBA tutorial, VBA tutorial Excel 2016. Excel has several other uses that may not have been covered here. Play around with visualize complex data or organize disparate numbers, to discover the infinite variety of functions in Excel. Strong knowledge of excel is a boon if you are looking forward to a career in data analytics.
A career in Excel VBA
Excel and Excel VBA both are used almost in all industries; Excel for reporting MIS, Data Analytics and research work whereas VBA is used to automate the Excel task to save time. Candidates with a strong knowledge of both Excel and VBA are never short of work. Since most multinationals need finance guys with a mathematics/accountancy background and a proficiency in Excel and Excel VBA. Qualified candidates may look for roles like MIS Analyst or Reporting Analyst. Since MS Excel is getting enriched with newer features and functionalities, updating your technical skills and database automation becomes imperative for a steady career growth.
Enrolling for an Excel VBA tutorial will open new doors of opportunities for you. We offer one of the best-known courses in the Certified Data Analytics Course. The course enables you to learn tools such as Advanced Excel, PowerBI, and SQL. The live projects and intensive training programme also empower you to come up with solutions for real-life problems.
Visual Basic for Applications (VBA) in Excel, is a powerful and sophisticated built-in programming language that allows you to write your own functions or commands in an Excel spreadsheet.
These custom functions or commands, can help to ease your tasks and thus by using Excel VBA you can do almost any imaginable thing in Excel.
Now, before we dive deep into Excel VBA, let’s first try to understand what VBA is.
What is VBA?
In most simple terms you can also say that, VBA is the language that Office Applications like Excel, Word, PowerPoint, etc. understand. So, all the programming that we are going to do in Excel or in other office application has to be done in VBA.
But technically, VBA is an implementation of Microsoft’s event-driven programming language i.e. VB6 and its associated integrated development environment (IDE).
VBA is an extensible programming language that is made up of a core set of commands and extended on a per-application basis to be able to work directly with objects in that application. And because of this it is sometimes also called as a hosted language.
Visual Basic for Applications is bundled with office applications (host application) so that it can be used as medium for accessing and interacting with the host applications object model. This means that, Excel VBA, knows about things like workbooks, worksheets, cells and charts, but Word VBA doesn’t knows about such things. Instead Word VBA understand terms like documents, bookmarks etc., things that are more related to Microsoft Word.
Is there any difference between a VBA Program and Macro?
I have seen many people confusing between VBA and Macro language. But a Macro language is very much different from a VBA. Macros were used with the older versions of office applications and they could only be used for automating instructions.
In fact, the first spreadsheet macro programs were just shortcuts for the user interface commands. For example, if in the user interface you typed R (for “Range”), N (for “Name”), and C (for “Create”), you would enter RNC into the macro to automate the process.
This approach was intuitive, but it also had integral weaknesses. Because of such weaknesses, VBA later in 1993 replaced this Macro Language, and hence there is still a misconception among people to call VBA as macro language.
Visual Basic for Applications when compared to traditional Macro Language is more powerful and sophisticated and hence it was an instant success.
Why learning Excel VBA is so important?
As you become familiar with Excel, you will notice that although Excel provides you large number of tools, but still it doesn’t have everything that you need to perform your daily tasks. Such tasks may include creating custom functions, repetitive instructions, automating tasks etc.
And hence Microsoft has provided VBA as a gap filler; that allows users to write their own methods or commands to perform their tasks.
After having enough experience with VBA programming in Excel you will never ever get stuck during your tasks due to a lack of built-in tools. Using Visual Basic for Applications you will be able to write your own function and commands whenever you feel the need to write one.
What all you can do with Excel VBA?
With Excel VBA you can do a lot of things in Excel. I have enlisted few of them below:
- You can automate the tasks that you have to do frequently.
- You can create a custom command in excel.
- You can repeat a set of instructions multiple times.
- You can create custom function popularly called as User Defined Function (UDF)
- You can create a custom add in in Excel.
Время на прочтение
7 мин
Количество просмотров 312K
Приветствую всех.
В этом посте я расскажу, что такое VBA и как с ним работать в Microsoft Excel 2007/2010 (для более старых версий изменяется лишь интерфейс — код, скорее всего, будет таким же) для автоматизации различной рутины.
VBA (Visual Basic for Applications) — это упрощенная версия Visual Basic, встроенная в множество продуктов линейки Microsoft Office. Она позволяет писать программы прямо в файле конкретного документа. Вам не требуется устанавливать различные IDE — всё, включая отладчик, уже есть в Excel.
Еще при помощи Visual Studio Tools for Office можно писать макросы на C# и также встраивать их. Спасибо, FireStorm.
Сразу скажу — писать на других языках (C++/Delphi/PHP) также возможно, но требуется научится читать, изменять и писать файлы офиса — встраивать в документы не получится. А интерфейсы Microsoft работают через COM. Чтобы вы поняли весь ужас, вот Hello World с использованием COM.
Поэтому, увы, будем учить Visual Basic.
Чуть-чуть подготовки и постановка задачи
Итак, поехали. Открываем Excel.
Для начала давайте добавим в Ribbon панель «Разработчик». В ней находятся кнопки, текстовые поля и пр. элементы для конструирования форм.
Появилась вкладка.
Теперь давайте подумаем, на каком примере мы будем изучать VBA. Недавно мне потребовалось красиво оформить прайс-лист, выглядевший, как таблица. Идём в гугл, набираем «прайс-лист» и качаем любой, который оформлен примерно так (не сочтите за рекламу, пожалуйста):
То есть требуется, чтобы было как минимум две группы, по которым можно объединить товары (в нашем случае это будут Тип и Производитель — в таком порядке). Для того, чтобы предложенный мною алгоритм работал корректно, отсортируйте товары так, чтобы товары из одной группы стояли подряд (сначала по Типу, потом по Производителю).
Результат, которого хотим добиться, выглядит примерно так:
Разумеется, если смотреть прайс только на компьютере, то можно добавить фильтры и будет гораздо удобнее искать нужный товар. Однако мы хотим научится кодить и задача вполне подходящая, не так ли?
Кодим
Для начала требуется создать кнопку, при нажатии на которую будет вызываться наша програма. Кнопки находятся в панели «Разработчик» и появляются по кнопке «Вставить». Вам нужен компонент формы «Кнопка». Нажали, поставили на любое место в листе. Далее, если не появилось окно назначения макроса, надо нажать правой кнопкой и выбрать пункт «Назначить макрос». Назовём его FormatPrice. Важно, чтобы перед именем макроса ничего не было — иначе он создастся в отдельном модуле, а не в пространстве имен книги. В этому случае вам будет недоступно быстрое обращение к выделенному листу. Нажимаем кнопку «Новый».
И вот мы в среде разработки VB. Также её можно вызвать из контекстного меню командой «Исходный текст»/«View code».
Перед вами окно с заглушкой процедуры. Можете его развернуть. Код должен выглядеть примерно так:
Sub FormatPrice()End Sub
Напишем Hello World:
Sub FormatPrice()
MsgBox "Hello World!"
End Sub
И запустим либо щелкнув по кнопке (предварительно сняв с неё выделение), либо клавишей F5 прямо из редактора.
Тут, пожалуй, следует отвлечься на небольшой ликбез по поводу синтаксиса VB. Кто его знает — может смело пропустить этот раздел до конца. Основное отличие Visual Basic от Pascal/C/Java в том, что команды разделяются не ;, а переносом строки или двоеточием (:), если очень хочется написать несколько команд в одну строку. Чтобы понять основные правила синтаксиса, приведу абстрактный код.
Примеры синтаксиса
' Процедура. Ничего не возвращает
' Перегрузка в VBA отсутствует
Sub foo(a As String, b As String)
' Exit Sub ' Это значит "выйти из процедуры"
MsgBox a + ";" + b
End Sub' Функция. Вовращает Integer
Function LengthSqr(x As Integer, y As Integer) As Integer
' Exit Function
LengthSqr = x * x + y * y
End FunctionSub FormatPrice()
Dim s1 As String, s2 As String
s1 = "str1"
s2 = "str2"
If s1 <> s2 Then
foo "123", "456" ' Скобки при вызове процедур запрещены
End IfDim res As sTRING ' Регистр в VB не важен. Впрочем, редактор Вас поправит
Dim i As Integer
' Цикл всегда состоит из нескольких строк
For i = 1 To 10
res = res + CStr(i) ' Конвертация чего угодно в String
If i = 5 Then Exit For
Next iDim x As Double
x = Val("1.234") ' Парсинг чисел
x = x + 10
MsgBox xOn Error Resume Next ' Обработка ошибок - игнорировать все ошибки
x = 5 / 0
MsgBox xOn Error GoTo Err ' При ошибке перейти к метке Err
x = 5 / 0
MsgBox "OK!"
GoTo ne
Err:
MsgBox
"Err!"
ne:
On Error GoTo 0 ' Отключаем обработку ошибок
' Циклы бывает, какие захотите
Do While True
Exit DoLoop 'While True
Do 'Until False
Exit Do
Loop Until False
' А вот при вызове функций, от которых хотим получить значение, скобки нужны.
' Val также умеет возвращать Integer
Select Case LengthSqr(Len("abc"), Val("4"))
Case 24
MsgBox "0"
Case 25
MsgBox "1"
Case 26
MsgBox "2"
End Select' Двухмерный массив.
' Можно также менять размеры командой ReDim (Preserve) - см. google
Dim arr(1 to 10, 5 to 6) As Integer
arr(1, 6) = 8Dim coll As New Collection
Dim coll2 As Collection
coll.Add "item", "key"
Set coll2 = coll ' Все присваивания объектов должны производится командой Set
MsgBox coll2("key")
Set coll2 = New Collection
MsgBox coll2.Count
End Sub
Грабли-1. При копировании кода из IDE (в английском Excel) есь текст конвертируется в 1252 Latin-1. Поэтому, если хотите сохранить русские комментарии — надо сохранить крокозябры как Latin-1, а потом открыть в 1251.
Грабли-2. Т.к. VB позволяет использовать необъявленные переменные, я всегда в начале кода (перед всеми процедурами) ставлю строчку Option Explicit. Эта директива запрещает интерпретатору заводить переменные самостоятельно.
Грабли-3. Глобальные переменные можно объявлять только до первой функции/процедуры. Локальные — в любом месте процедуры/функции.
Еще немного дополнительных функций, которые могут пригодится: InPos, Mid, Trim, LBound, UBound. Также ответы на все вопросы по поводу работы функций/их параметров можно получить в MSDN.
Надеюсь, что этого Вам хватит, чтобы не пугаться кода и самостоятельно написать какое-нибудь домашнее задание по информатике. По ходу поста я буду ненавязчиво знакомить Вас с новыми конструкциями.
Кодим много и под Excel
В этой части мы уже начнём кодить нечто, что умеет работать с нашими листами в Excel. Для начала создадим отдельный лист с именем result (лист с данными назовём data). Теперь, наверное, нужно этот лист очистить от того, что на нём есть. Также мы «выделим» лист с данными, чтобы каждый раз не писать длинное обращение к массиву с листами.
Sub FormatPrice()
Sheets("result").Cells.Clear
Sheets("data").Activate
End Sub
Работа с диапазонами ячеек
Вся работа в Excel VBA производится с диапазонами ячеек. Они создаются функцией Range и возвращают объект типа Range. У него есть всё необходимое для работы с данными и/или оформлением. Кстати сказать, свойство Cells листа — это тоже Range.
Примеры работы с Range
Sheets("result").Activate
Dim r As Range
Set r = Range("A1")
r.Value = "123"
Set r = Range("A3,A5")
r.Font.Color = vbRed
r.Value = "456"
Set r = Range("A6:A7")
r.Value = "=A1+A3"
Теперь давайте поймем алгоритм работы нашего кода. Итак, у каждой строчки листа data, начиная со второй, есть некоторые данные, которые нас не интересуют (ID, название и цена) и есть две вложенные группы, к которым она принадлежит (тип и производитель). Более того, эти строки отсортированы. Пока мы забудем про пропуски перед началом новой группы — так будет проще. Я предлагаю такой алгоритм:
- Считали группы из очередной строки.
- Пробегаемся по всем группам в порядке приоритета (вначале более крупные)
- Если текущая группа не совпадает, вызываем процедуру AddGroup(i, name), где i — номер группы (от номера текущей до максимума), name — её имя. Несколько вызовов необходимы, чтобы создать не только наш заголовок, но и всё более мелкие.
- После отрисовки всех необходимых заголовков делаем еще одну строку и заполняем её данными.
Для упрощения работы рекомендую определить следующие функции-сокращения:
Function GetCol(Col As Integer) As String
GetCol = Chr(Asc("A") + Col)
End FunctionFunction GetCellS(Sheet As String, Col As Integer, Row As Integer) As Range
Set GetCellS = Sheets(Sheet).Range(GetCol(Col) + CStr(Row))
End FunctionFunction GetCell(Col As Integer, Row As Integer) As Range
Set GetCell = Range(GetCol(Col) + CStr(Row))
End Function
Далее определим глобальную переменную «текущая строчка»: Dim CurRow As Integer. В начале процедуры её следует сделать равной единице. Еще нам потребуется переменная-«текущая строка в data», массив с именами групп текущей предыдущей строк. Потом можно написать цикл «пока первая ячейка в строке непуста».
Глобальные переменные
Option Explicit ' про эту строчку я уже рассказывал
Dim CurRow As Integer
Const GroupsCount As Integer = 2
Const DataCount As Integer = 3
FormatPrice
Sub FormatPrice()
Dim I As Integer ' строка в data
CurRow = 1
Dim Groups(1 To GroupsCount) As String
Dim PrGroups(1 To GroupsCount) As String
Sheets(
"data").Activate
I = 2
Do While True
If GetCell(0, I).Value = "" Then Exit Do
' ...
I = I + 1
Loop
End Sub
Теперь надо заполнить массив Groups:
На месте многоточия
Dim I2 As Integer
For I2 = 1 To GroupsCount
Groups(I2) = GetCell(I2, I)
Next I2
' ...
For I2 = 1 To GroupsCount ' VB не умеет копировать массивы
PrGroups(I2) = Groups(I2)
Next I2
I = I + 1
И создать заголовки:
На месте многоточия в предыдущем куске
For I2 = 1 To GroupsCount
If Groups(I2) <> PrGroups(I2) Then
Dim I3 As Integer
For I3 = I2 To GroupsCount
AddHeader I3, Groups(I3)
Next I3
Exit For
End If
Next I2
Не забудем про процедуру AddHeader:
Перед FormatPrice
Sub AddHeader(Ty As Integer, Name As String)
GetCellS("result", 1, CurRow).Value = Name
CurRow = CurRow + 1
End Sub
Теперь надо перенести всякую информацию в result
For I2 = 0 To DataCount - 1
GetCellS("result", I2, CurRow).Value = GetCell(I2, I)
Next I2
Подогнать столбцы по ширине и выбрать лист result для показа результата
После цикла в конце FormatPrice
Sheets("Result").Activate
Columns.AutoFit
Всё. Можно любоваться первой версией.
Некрасиво, но похоже. Давайте разбираться с форматированием. Сначала изменим процедуру AddHeader:
Sub AddHeader(Ty As Integer, Name As String)
Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow)).Merge
' Чтобы не заводить переменную и не писать каждый раз длинный вызов
' можно воспользоваться блоком With
With GetCellS("result", 0, CurRow)
.Value = Name
.Font.Italic = True
.Font.Name = "Cambria"
Select Case Ty
Case 1 ' Тип
.Font.Bold = True
.Font.Size = 16
Case 2 ' Производитель
.Font.Size = 12
End Select
.HorizontalAlignment = xlCenter
End With
CurRow = CurRow + 1
End Sub
Уже лучше:
Осталось только сделать границы. Тут уже нам требуется работать со всеми объединёнными ячейками, иначе бордюр будет только у одной:
Поэтому чуть-чуть меняем код с добавлением стиля границ:
Sub AddHeader(Ty As Integer, Name As String)
With Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow))
.Merge
.Value = Name
.Font.Italic = True
.Font.Name = "Cambria"
.HorizontalAlignment = xlCenterSelect Case Ty
Case 1 ' Тип
.Font.Bold = True
.Font.Size = 16
.Borders(xlTop).Weight = xlThick
Case 2 ' Производитель
.Font.Size = 12
.Borders(xlTop).Weight = xlMedium
End Select
.Borders(xlBottom).Weight = xlMedium ' По убыванию: xlThick, xlMedium, xlThin, xlHairline
End With
CurRow = CurRow + 1
End Sub
Осталось лишь добится пропусков перед началом новой группы. Это легко:
В начале FormatPrice
Dim I As Integer ' строка в data
CurRow = 0 ' чтобы не было пропуска в самом начале
Dim Groups(1 To GroupsCount) As String
В цикле расстановки заголовков
If Groups(I2) <> PrGroups(I2) Then
CurRow = CurRow + 1
Dim I3 As Integer
В точности то, что и хотели.
Надеюсь, что эта статья помогла вам немного освоится с программированием для Excel на VBA. Домашнее задание — добавить заголовки «ID, Название, Цена» в результат. Подсказка: CurRow = 0 CurRow = 1.
Файл можно скачать тут (min.us) или тут (Dropbox). Не забудьте разрешить исполнение макросов. Если кто-нибудь подскажет человеческих файлохостинг, залью туда.
Спасибо за внимание.
Буду рад конструктивной критике в комментариях.
UPD: Перезалил пример на Dropbox и min.us.
UPD2: На самом деле, при вызове процедуры с одним параметром скобки можно поставить. Либо использовать конструкцию Call Foo(«bar», 1, 2, 3) — тут скобки нужны постоянно.