Understanding the differences between VBA and Visual Basic .NET can help you make a more informed decision about converting your code. This section examines differences in the following areas:
- Language
- Project management
- Security
- Deployment
Language Differences
Because Visual Basic .NET was designed to take advantage of the .NET Framework, it contains many changes and areas where compatibility with previous versions of the language has not been preserved. The following is a partial list of changes to the Visual Basic language in Visual Basic .NET. For more information, see Introduction to Visual Basic .NET for Visual Basic Veterans.
Late Binding. VBA and Visual Basic .NET support late binding; however, using early-bound objects makes your code easier to read and maintain and enables IntelliSense. Visual Basic .NET introduces the Option Strict On statement, which enforces early binding and prevents implicit conversion where data might be lost. The compiler default is Option Strict Off. One reason this is important is that many of the methods and properties of Office objects return the type Object, and you must explicitly convert the object to the correct type, as shown in the following example:
' Using Ctype to convert the Object.returned by Sheet1 to a Worksheet.
MsgBox(CType(ThisWorkbook.Worksheets("Sheet1"), Excel.Worksheet).Name)
Declaring Variables. In VBA, you can use the Option Explicit statement to enforce explicit variable declaration. You can also set this automatically by selecting the Require Variable Declaration check box in the VBA IDE options, which by default is not selected. All implicitly declared variables are of Variant type.
The Visual Basic .NET compiler enforces explicit declaration, requiring that every variable be declared. You can override this by using the statement Option Explicit Off. All implicitly declared variables are of Object type. You should consider this when copying and pasting code from VBA to Visual Basic .NET, because the Variant data type is no longer supported and will automatically be converted to the Object data type. You should explicitly type all variables declared in your project.
Default Properties. In Visual Basic .NET, default properties are only supported if the properties take arguments. In VBA, you can use shortcuts when typing code by eliminating the default properties. For example:
ActiveDocument.Tables(1).Cell(1, 1).Range = "Name"
When converting this code to Visual Basic .NET, you must type out the default property of the Range object, which is Text:
ThisApplication.ActiveDocument.Tables(1).Cell(1, 1).Range.Text = "Name"
Note that the default property for the Tables object, Item, is not required because it takes an index parameter. However, your code will be more readable if you include all of the default properties:
ThisApplication.ActiveDocment.Tables.Item(1).Cell(1, 1).Range.Text _
= "Name"
ByVal, ByRef Parameters. In VBA, parameters are passed by reference by default. In Visual Basic .NET, parameters are passed by value by default. When preparing your code for conversion to Visual Basic .NET, you might want to check that all methods explicitly define whether the parameters should be passed by reference or by value. When you paste code into the Visual Studio .NET IDE with parameters that are not defined,ByVal is automatically added to each parameter in the list.
Enumerations. Enumeration constants must be fully qualified in Visual Basic. NET. When converting your VBA code, you must add the fully qualified enumeration name to both Word and Excel constants. For example, when performing a search in Word VBA, you specify the FindWrapvalue of the Selection or Range using a wd constant. Three options are given: wdFindStop, wdFindAsk, and wdFindContinue. In VBA, you can simply assign the constant because the enumeration is global to your project:
Selection.Find.Wrap = wdFindContinue
In Visual Basic .NET, you must fully qualify the constant with the enumeration name:
ThisApplication.Selection.Find.Wrap = Word.WdFindWrap.wdFindContinue
This may seem like a lot of extra typing, but if you use the IntelliSense feature of Visual Studio .NET, locating and typing the qualified constants is relatively easy, and it makes your code more readable. If you are already familiar with the constant names, you will find that the enumeration name often closely matches the constant name. In the case above, they both contain wdFind. To explore the available enumerations, type Word.Wd and scroll through the items available in the IntelliSense drop-down list (type Excel.XL to scroll through the list of available enumerations for Excel).
Non-Zero Bound Arrays. In VBA, the default lower bound of an array dimension is 0 (zero). Using Option Base, you can change this to 1. In Visual Basic .NET, the Option Base statement is not supported, and the lower bound of every array dimension must be 0. Additionally, you cannot use ReDim as an array declaration. One thing to keep in mind when working with Office collections from Visual Basic .NET is that the lower array bounds of most Office collections begin with 1.
Use of Parentheses with Method Calls. In VBA, parentheses are optional in some cases when you call subroutines, and it is sometimes difficult to remember when they are required. In Visual Basic .NET, parentheses are required when passing parameters in a method call.
Set Keyword. In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object. Since default properties are not supported in Visual Basic .NET, the Set keyword is not needed and is no longer supported. This change is illustrated in the following examples:
' VBA
Dim mySelection as Selection
Dim myOtherSelection as String
Set mySelection = Selection
myOtherSelection = Selection
' Visual Basic .NET
Dim mySelection As Word.Selection
Dim myOtherSelection As String
mySelection = ThisApplication.Selection
myOtherSelection = ThisApplication.Selection.Text
Data Access. Data binding to a Data Access Object (DAO) or Remote Data Object (RDO) data source is not supported in Microsoft Visual Basic .NET. ActiveX® Data Objects (ADO) data binding is supported for backward compatibility; however, you may want to consider converting to ADO.NET. For more information, see Comparison of ADO.NET and ADO.
Conversion of UserForms to Windows Forms. VBA UserForms cannot be copied or imported into Visual Studio .NET. In most cases, you will need to recreate your forms as Windows Forms. The use of drag-and-drop controls is consistent with creating forms in VBA, but event handlers for Windows Form controls are handled differently. Many new features are available to make creating your forms easier than before, for example:
- Control anchoring is now possible, so that when a user resizes your form, the controls automatically resize and reposition properly.
- Setting tab order is much easier with Windows Forms. Enable tab ordering by clicking Tab Order on the View menu. Then simply click each control in the preferred order.
- Creating menus in-line is an improvement over menu creation in VBA.
- In VBA, you can show a form as vbModal or vbModeless. In Visual Basic .NET, the ShowDialog method is used to display a form modally; the Show method is used to display a form non-modally. Note, however, that the form will display non-modally, but when you click in the Word or Excel document, the form moves to the background, which can be confusing to your users.
- Many new form controls are also available in Visual Basic .NET, such as data-entry validators, common dialog boxes, hyperlinked labels, system tray icons, panels, numeric-up/downs, on-the-fly designable tree views, Help file linkers, ToolTip extenders, and more
Project Management Differences
When you start using Visual Basic .NET to create your Office solutions, one difference you will notice is the location of the code in your project. When you use VBA to create an Office solution, the code resides in modules, UserForms, and class modules within a Word template, Word document, or Excel workbook. When you use Visual Studio Tools for the Microsoft Office System, the code resides in classes and Windows Forms, which are compiled into an assembly, and is referenced by the Word or Excel document.
The Visual Studio .NET IDE has enhanced functionality, but it is similar to the VBA IDE in many ways. Each has an explorer for viewing projects, modules, forms, and references. Each provides a properties window, toolbox, object browser, and debugging capabilities. Table 1 lists some differences you might notice when managing your projects.
Table 1. Differences in the VBA and Visual Studio .NET IDE
| VBA IDE |
Visual Studio .NET IDE |
| Project Explorer contains a dynamic list of all of the projects (templates, documents, and add-ins) that are currently open. |
Solution Explorer contains a static list of one or more projects in the open solution. |
| Project files are stored in subfolders: UserForms, modules, and class modules. |
Project files are stored alphabetically and are not categorized into subfolders. |
| In Word, the project contains a folder that shows the references to global templates. In Word and Excel, external references are set using theReferences command on the Tools menu.
If you create a Web reference using the Web Services Toolkit, classes are created for the Web service and all of its methods. The classes are located in the Class Modules folder.
|
The project contains a folder that shows the references you have set using the Add Reference command on the Projects menu.
If you create a Web reference, the reference is located in the Web References folder.
|
| Project files have distinct file extensions: UserForms (.frm), class modules (.cls), and modules (.bas). |
Project files for forms, modules, and class modules all have the same .vb extension. Supporting files have other extensions (.xml, .aspx, and so on.). |
| In a VBA solution for a Word template or document, ThisDocument is located in the Microsoft Word Objects folder.
In a VBA solution for an Excel Document, ThisWorkbook and the worksheets are located in the Microsoft Excel Objects folder.
|
Visual Basic .NET Word projects contain a ThisDocument code file.
Visual Basic .NET Excel projects contain a ThisWorkbook code file.
|
Another difference that you will find is in the use of ActiveX controls. In VBA, ActiveX controls are top-level objects and have IntelliSense support. In Visual Basic .NET, you must define variables for the controls, use the FindControl method in Visual Studio Tools for the Microsoft Office System, and convert them to a strong type in order to access IntelliSense.
Security Differences
The Microsoft .NET Framework provides security features that you cannot take advantage of in VBA. In VBA, there are three basic security options:
- Set the security settings to high on user machines and digitally sign your code.
- Let the user decide whether or not to trust the code when presented with the macro virus warning.
- Set the security to low to allow all code to run (including malicious code). Note that this third option should never be used.
Word and Excel documents with managed code extensions that are created using Visual Basic .NET do not use Office macro security, which relies on the Office certificate store. They incorporate the standard security features available in the Microsoft .NET Framework 1.1, for example:
- Code signing is no longer necessary, as there are several types of evidence that are available for security in .NET Framework, including Application Directory, Strong Name, URL, and more.
- Administrators can use standard tools to set security policies. The security policy must grant full trust to an assembly or the code cannot execute.
- The end user cannot change security options within Word or Excel to permit untrusted code to run. If the end user opens a document with untrusted code, the code will not run.
For more information on setting security in the .NET Framework, read the Visual Studio Tools for the Microsoft Office System help topic, “Security in Office Solutions That Use Managed Code Extensions,” or see An Overview of Security in the .NET Framework.
Deployment Differences
Deploying Visual Basic .NET applications is quite different from deploying VBA applications. Visual Studio Tools for the Microsoft Office System projects usually consist of two files: the assembly, which contains the compiled code, and the document (Excel worksheet or Word document or template), which contains custom properties that point to the assembly. The document and assembly are deployed separately. Unlike many VBA projects where the code is embedded in the document, in Visual Studio Tools for the Microsoft Office System projects, the assembly can be stored in a shared network location, or it can be copied to each end user’s computer. The advantage in deploying an assembly to a network location is that it is easier to update the code because you will have only one copy of the assembly on the network share. Users can modify and customize their copy of the document and will have access to the updated assembly every time the document is opened. This happens automatically, with no user intervention.