1.4. Object Models: The Power of Programming with VBA
VBA is a single language, although when comparing code taken from a VBA program written for Word with one written for Access or Visual Basic, you could be forgiven for thinking you are reading code from two very different languages. This is because VBA interfaces with an application's object model, and much of the time the code you write references objects that are unique to the host application. To demonstrate this, in the VBA code fragments shown in Examples Example 1.1 through Example 1.4, generic VBA code is shown in a normal typeface, object code that is unique to the application is shown in bold, and variables are shown in italics.
Example 1.1. A Code Snippet from an Excel VBA Program
For Each c In Worksheets("Sheet1").Range("C4:C17").Cells If c.Value = iCond Then tempTot = tempTot + c.Offset(0, 1).Value End If Next c |
Example 1.2. A Code Snippet from a Word VBA Program
Set myRange = ActiveDocument.Range( _ Start:=ActiveDocument.Paragraphs(2).Range.Start, _ End:=ActiveDocument.Paragraphs(2).Range.End) myRange.Select myRange.Bold = True |
Example 1.3. A Code Snippet from an Access VBA Program
Form_Form1.RecordSource = "SELECT Products.ProductCode, " _ & " Products.BinLocation, Descriptions.Description" _ & " FROM Products INNER JOIN Descriptions " _ & " ON Products.ProductCode = Descriptions.ProductCode" _ & " WHERE (((Descriptions.Language)=" & iLangCode & "));" Text0.ControlSource = "ProductCode" |
Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.