Featuring the Leszynski Naming Conventions
by Stan Leszynski
Kwery Corporation
Copyright © 1995 Kwery Corporation, Bellevue, WA, All Rights Reserved
Created: November 20, 1995
Stan Leszynski founded Leszynski Company Inc. in 1982 to create custom PC database applications. Since that time, the firm has created solutions for hundreds of clients, including Microsoft. The company has also written retail products sold by Microsoft, Microrim, Qualitas, and Kwery with a user base of several million people, including the OLE calendar controls shipped with Access 2 and Access 95. The company currently specializes in Microsoft Access, Visual Basic, SQL Server, and Visual C++ development. Stan's second company, Kwery Corporation, shipped the very first Access add-in — Access To Word — and the first OLE controls for Access 2.0 — Kwery Control Pak 1.
Stan is the author of the book Access Expert Solutions from Que. He is also a monthly columnist on developer issues for Access/Visual Basic Advisor magazine, and has written for PC Magazine and Smart Access Journal. He speaks regularly at Access and Visual Basic conferences in North America and Europe, and is consistently one of the top-rated Access speakers.
As your Microsoft® Office Visual Basic® for Applications (VBA) development becomes more sophisticated, you invariably create reusable systems based on objects and techniques that have proven successful for yourself or fellow developers. As a consequence, you will probably eventually create or adopt a set a standardized object naming conventions.
Creating your own naming conventions takes a large amount of research, development, and testing effort. The challenge of creating your own conventions is compounded by the rapidly increasing complexity of the Microsoft Office object model. To complicate matters even further, there are several different stylistic approaches you can take when naming objects (identifier styles and location, length and structure of object names, and so forth).
This document provides you with two tools to use as you create a consistent development style for object names:
This document includes some elements of LNC that you can use for Access, Excel, and Word development.
This document is an abstract condensed from the full Leszynski Naming Conventions documentation. The information provided is to introduce you to the concept of naming conventions and the structure of LNC — the full LNC documentation is too lengthy to reproduce here. See the end of this document for information on how to obtain full LNC documents and tools.
Naming conventions are one of the foundation elements of your overall development style. You usually decide to adopt a naming convention to achieve one or more of these objectives:
For me, an application filled with object names that do not follow a consistent style is as difficult to navigate through as a messy garage! In contrast, an organized application is easier to understand, even if you didn't develop it. For example, try to determine in Figure 1 which forms are standard forms, which one is the switchboard menu, which ones are for lookup tables, and which forms are actually subforms.
Figure 1. These form names follow specific naming conventions
Notice that two types of naming conventions are evident in the figure. The first convention is the standardization of the object base names. All customer and dealer objects contain Cust and Dealer, respectively, in their base names, and these root elements of the names are placed at the beginning of the base name so that customer and dealer objects each sort with their peers. The second, and equally important, convention is the addition of leading characters denoting the type of the forms. Many naming conventions have in common the standardization of the base object name and the addition of descriptive information on one or both ends of the base name.
The example provided by the form names in the figure is equally applicable to the other named elements of an application. Any object in your application that you will view or refer to frequently — database objects, form and report controls, procedure names, and Basic variables — is a candidate for naming conventions. The fact that you may see and use a particular object's name dozens or hundreds of times throughout a development project further accentuates the need for developing good rules for naming objects. Any name you see and use over and over should be both informative and logical.
The motivation to create naming conventions for working with your development tools usually derives from specific problems or situations you encounter. Here are a few compelling reasons for developing and using naming conventions in your applications:
Here are three considerations to keep in mind if you develop your own naming style:
These three points are general in nature. In addition, there are several very specific considerations that you must weigh when creating a naming convention for your Microsoft Office-centric solutions. These issues are covered in the next four topics.
A base name is the name you would give an object before applying naming convention elements. A strategy for selecting, abbreviating, capitalizing, and organizing object base names is, in and of itself, a naming convention. Thus if you do nothing more than create a consistent approach to base names, you have authored a development style for yourself. What topics would you include in a convention for base names? Consider, at least:
For example, WidgetProductionStatisticsFirstQuarter1994 is a perfectly legitimate and descriptive Access table name. However, after applying base name rules from LNC, I end up with the name WidgetStats94Q1, which is shorter, equally descriptive, and sorts better with respect to related objects.
When creating your own naming conventions, you will have to determine what characters are allowed, what punctuation is legal, and what the capitalization standards are. For example, while most developers use mixed-case capitalization in object names, a few do not. Access developers that also work in SQL Server traditionally preferred lowercase names for tables and fields, so that any of their applications could be "upsized" to the server, which did not support mixed-case prior to version 6.0. Also, I have met many developers who are religious about economizing keystrokes. Such people often work with lower-case object names, to save their "pinkie" fingers thousands of visits to the Shift key on the keyboard each day. Finally, some people simply can't read object names clearly even with mixed-case; they prefer punctuation such as underscores in names instead.
For myself, I prefer a mix of upper and lower case, and I am basically sour on any kind of punctuation in object names except for underscores (no space, no dashes, etc.). This ensures that I can move data from an Access or Jet back-end to other platforms without any renaming (for example, SQL Server allows only letters, digits, $, #, and underscores in names, and Visual FoxPro™ is even more restrictive).
Using standardized abbreviations can be useful when trying to shorten object names without a loss of meaning. Typically, when the design phase of an application is completed, and object names such as table and field names are being finalized, you should look for opportunities to create and/or apply standard abbreviations. You will need to devise rules for creating abbreviations, and create a list of common abbreviations for reuse.
Abbreviations that we use ourselves tend to fall in the three to five character range, although some variances occur for clarity. Few words require more than five characters to convey the original word with no loss of readability or meaning.
Recall the previous example where I shortened the table name from WidgetProductionStatisticsFirstQuarter1994 to WidgetStats94Q1. Why did I select this particular order for segments of the name? I did it with sorting in mind.
By design default, when Microsoft Office lists object names, they are usually sorted alphabetically. If you name related objects (those with similarities in the base name) so they sort close together, they appear consecutively in ordered lists. In the example at hand, I changed the trailing FirstQuarter1994 portion of the example table name to 94Q1, a convention that ensures that similar object names will sort by year, then quarter, producing a list like this:
WidgetStats94Q3
WidgetStats94Q4
WidgetStats95Q1
WidgetStats95Q2
In my example, I had to decide that the "WidgetStats" portion of the name was the most important with respect to sorting, then the year and quarter. As you create conventions, you must determine if sort order is important, and how object name components will be assembled to achieve the desired ordering.
When you have debated the various general considerations for naming conventions and devised your strategy for object names, you can proceed to creating the wrappers around the names that provide extra information and capabilities. The most important of these are called tags, which are characters placed against an object name to categorize it. Figure 2 shows tags in use on Access forms and controls.
Figure 2. The form controls in this list are easily identified by their three-character tags
The challenges for you as you define your naming style are to define:
Why use tags at all? In an environment like Microsoft Office, where terms like object, class, and property are becoming more and more important, a base name by itself does not convey enough information for many developers. It can be very convenient to encapsulate within an object's name information about the type of the object (in other words, its class and/or other primary properties).
Tags can be placed before (as in qryCust or qdelCustClosed) or after (as in CustQry or CustClosed_QDel) an object's base name. The placement of tags can become a hotly debated issue as you standardize: "Are tags that precede a name better for us than those that follow the name?" As you can determine from the two figures earlier in this document, tags placed before objects in sorted lists cause them to sort by type before name. Some programmers, however, prefer to scan an object list and see the base name as the primary sort order. With such individuals around, you might opt for trailing tags instead.
If you have decided to use tags, you next need to determine which objects should be tagged. Some developers prefer to use tags only for program variables and structures, while others place tags on every application object, such as controls and tables.
Some developers use tags that are as short as a single character. While this certainly economizes on keystrokes, such tags are not very intuitive except in limited cases. I feel that one-character tags are too obscure and limiting (the limit is the 26 letters of the alphabet, which doesn't allow enough room for growth).
Most developers find that three and four character tags prove more useful than single-character and double-character strings. This tag length is the most prevalent across the majority of published Microsoft Office styles, although users of this length admit that it introduces some extra keystrokes into development efforts.
Table 1 below shows several different tags for selected Access objects, culled from various naming convention documents that have been sent to me by Access developers over the previous two years. Note that none of the tags exceed four characters in length, and that different developers often come up with very similar tags.
Table 1. Selected Tags from Various Access Naming Conventions
Object Type |
Tag |
QueryDef Variable |
q |
QueryDef Variable |
q_ |
QueryDef Variable |
qd |
QueryDef Variable |
qdf |
QueryDef Variable |
qdf_ |
QueryDef Variable |
qry |
String Variable |
s |
String Variable |
s_ |
String Variable |
str |
String Variable |
str_ |
String Variable |
sz |
The best approach to use when deciding on a placement strategy for tags such as these is to create two small, similar applications. Use the leading tag convention in one, and the trailing tag convention in the other, and perhaps differing tag lengths as well. Comparing the pluses and minuses of the two approaches after actually using them in a hands-on experiment is the best input for making your decision.
Once you have decided on a tagging strategy that includes length and placement, the tags themselves need to be created. Below are four rules of thumb that I suggest you apply to the process.
If you've gotten the impression that there is no single, simple rule for creating tags, you're right. The process is unique to your needs and experience as an individual developer or development team.
By definition, a tag describes the type of the object. However, some objects can have attributes (essentially properties) other than their type that give them additional capabilities. For example, a VBA variable can have a scope of Public or Private, in addition to its data type. It may be helpful to you to denote scope with a character in front of the tag, like this:
Public pintTotal As Integer
In your naming conventions, you should consider whether or not it is important to add such identifiers to your tags to describe scope and similar attributes. I call an identifier that precedes a tag a prefix, which we essentially define as "a one or two-character clarification tag placed on an object tag".
A qualifier is a naming extension that provides context to the specific use of an object. For example, assume you need three Basic variables to track movement through an array: the first item, the current item, and the last item. You could consider using the qualifiers First, Curr, and Last at the end of the object names to make the names unique and their purpose obvious, while retaining the same base name:
iaintPartCurr
iaintPartFirst
iaintPartLast
Placing the qualifier after the base name like this allows the object base names (Part) to sort together. An alternate construction would place the qualifiers after the tags rather than the base name, to drive the sort order differently. This would yield names like iaintCurrPart.
Some naming conventions also allow for a suffix added to the end of the name, such as in the example qsumSalesmanPerfBest_AK, where Best is a qualifier and AK (Alaska) is a suffix. A suffix provides a finer level of detail than a qualifier. You will have to determine if your style needs either or both of these extra devices.
If you adopt or create a set of naming conventions, should you apply it retroactively to any existing applications? The answer depends on these two questions:
The next section of this document describes an actual naming convention used by myself and my development staff as we build Microsoft Office applications. It was designed following the principles and approaches illustrated in this section.
LNC was born of necessity, since most members of my staff spend all day developing Microsoft Office-centric applications, year after year. When we went "shopping" for an Office naming convention years ago, we discovered a void in the marketplace — there was no consensus about development styles among leading Microsoft Solution Providers. So we created our own style.
LNC provides a set of consistent naming conventions to add to these Microsoft Office/BackOffice application objects:
LNC is based on the use of leading tags — several characters placed before an object's name (for example, frmCust). This approach is sometimes referred to as "Hungarian notation", named for the nationality of a C programmer at Microsoft who published a treatise on tags for C about ten years ago.
Leading tags provide the following benefits over trailing tags (and over no tags):
LNC provides an integrated approach to working with multiple products. We have addressed many of the challenges that arise when working with the various Microsoft tools, such as how to name objects that are functionally similar but have different class names, and vice-versa.
In LNC, object names are constructed using this syntax:
[prefix(es)] tag [BaseName] [Qualifier] [Suffix]
The brackets indicate optional syntax elements — do not include them in your actual object names. Notice that the tag element is required even though the BaseName is not (in some cases). These options will be explained later in this document. In the syntax diagram, the case of each element reflects its case in actual use — the element tag is in lower case since the tags themselves are always lower case.
Table 2 shows sample object names using these LNC constructions.
Table 2. Object Names Constructed in LNC Format
Object Name |
Prefixes |
Tag |
BaseName |
Qualifier |
Suffix |
frmCust |
frm |
Cust |
|||
qsumSalesPerfBest_WA |
qsum |
SalesPerf |
Best |
_WA |
|
plngRecNumMax |
p |
lng |
RecNum |
Max |
|
iaintPartNum |
ia |
int |
PartNum |
See the section "Developing Naming Convention Elements" earlier in this document for an explanation of prefixes, tags, base names, qualifiers, and suffixes. The usage of these elements in LNC is as follows:
The engine of your Microsoft Office applications is Visual Basic for Applications code. In LNC, both the base name and the tag are considered important components. Thus, the syntax Dim I As Integer for a loop variable becomes Dim iintLoop As Integer — a variable name that clearly represents an integer variable indexing a loop.
Crafting VBA object base names involves creating and following simple rules such as these:
Wherever possible, variable names should contain a reference to objects of any type that they relate to. For example, a Recordset variable created on tblCust should be named rstCust.
There is no LNC guideline limiting variable name length, but common sense dictates that variable names longer than 15 or 20 characters waste a lot of keystrokes at each use. For procedure names, the VBA module editor by default show the first 30 characters of a procedure name, so this number is suggested as the target maximum procedure name length.
Abbreviate VBA object base name elements wherever possible by creating and reusing a set of standardized abbreviations.
Procedure base names in LNC follow the construction ObjectVerb, where the Object portion describes the primary object type affected (often the same as the primary argument), and Verb describes the action. This style sorts functions and subs by their target object when shown in ordered lists:
FormCtlHide
FormCtlShow
FormPropAdd
FormPropGet
FormPropSet
A common alternative construction uses a VerbObject metaphor, in which the previous object names would list like this:
AddFormProp
GetFormProp
HideFormCtl
SetFormProp
ShowFormCtl
LNC recognizes and accepts that many developers prefer the VerbObject metaphor, especially for OLE Automation server applications. You should experiment with both constructions and choose the one that works best for you.
In LNC, tags are required for the following VBA objects:
Optional tags also are available for some types of procedures.
In the syntax diagram earlier we noted that base names are optional in some constructions. When you are programming in VBA, the tag element is always required, but the base name is optional for variables local to a procedure. For example, a procedure that declares only one form object variable can legitimately use the variable name frm, which is a tag without a base name. Normally, however, I prefer more detail. Type structures, constants, and variables that have module-level or public scope must have both a tag and base name.
VBA variable tags are noted in the following table.
Table 3. Tags for VBA Data Variables
Variable Type |
Tag |
Boolean |
bln |
Byte |
byt |
Conditional Compilation Constant |
ccc |
Currency |
cur |
Date |
dtm |
Double |
dbl |
Error |
err |
Integer |
int |
Long |
lng |
Object |
obj |
Single |
sng |
String |
str |
User-Defined Type |
typ |
Variant |
var |
Instead of using I and J as work variable names, use names that are still short but meaningful, such as iintLoop and strSQL.
The prefixes for VBA variables can be categorized into two groups: prefixes for scope, and all other prefixes. The following prefixes are ordered by increasing (broader) scope.
|
|
|
|
|
|
|
|
|
|
When used, scope prefixes always begin a variable name and precede any other prefixes.
In addition to scope, other characteristics of variables can be identified by prefixes, such as procedure argument types, object references, and so forth.
VBA 95 introduced some changes in the area of constants. The changes most relevant to naming conventions include these:
When creating constants, use one of the scope prefixes (if appropriate), the prefix c, and the suitable tag for the constant's data type, as in gcstrUserName. To properly synchronize the tag, the data type, and the value, I do not let VB assign the type — LNC says to always use the full Const name As datatype syntax.
Whether and how to prefix and tag procedure names is a debatable subject. In general, LNC neither requires nor encourages placing characters before a procedure name, except in the following situation.
Procedures can have scope similar to that of variables — s (Static), m (Private), p (Public), or g (global Public). LNC allows, but does not encourage, the use of these scope prefixes on function names if they solve a particular need, and are used consistently throughout an application.
If you are creating code libraries for retail sale, for inclusion in the public domain, or for broad distribution in some other manner, consider whether or not your object names might share a name space and conflict with objects of the same name already in the user's project. If this is a possibility, LNC recommends that you prefix Public variables, constants, and procedures with a unique author prefix identifying you, your company, or the application. The prefix consists of two to four unique characters (optionally followed by an underscore), and prevents your object names from conflicting with object names in the host application, or in other referenced or referencing applications on a user's machine.
Bear in mind that an author prefix will affect the sorting of objects and should only be used to solve specific compilation problems.
To create an author prefix, use your personal or company initials. For example, author prefixes for my companies are lci_ for Leszynski Company, Inc. and kwc_ for Kwery Corporation. Before using your selected prefix, make an effort to determine if the prefix is already widely in use.
With the large number of methods and properties listed in the Object Browser for most type libraries, differentiating built-in attributes of objects from those added during development can be a challenge. Procedure tags in class, form, and report modules add a high degree of order to working with user-defined elements in the Object Browser (and other sorted lists), by clearly grouping custom procedures, methods, and properties apart from built-in object attributes.
On the other side of the coin, some developers feel strongly that procedure names should not have tags, especially in OLE Automation server applications. Before you blindly accept or condemn the use of tags in this context, try it awhile and then decide for yourself.
The LNC style prescribes the following naming convention tags for procedures:
|
|
|
|
|
|
LNC does not require or suggest assigning a data type tag to functions to reflect their return value. However, if you have a specific need to tag procedures to reflect their return value type, use the appropriate tags from the prior "Tags for VBA variables" section, and apply them consistently to all procedures in an application.
The following table shows examples of VBA variables applying the various conventions for VBA objects.
Table 4. VBA Variable Name Examples
Declaration |
Description |
Function lci_ArraySum (ParamArray ravarNum() As Variant) As Double |
Company identifier |
Public giaintPartNum As Integer |
Global index into array |
Const clngCustNumMax As Long = 10000 |
Const for max CustID |
Function FileLock(ByVal vstrFile As String) As Boolean |
ByVal argument |
Your Microsoft Office applications can use OLE Automation from VBA code to access objects that are not in the current code's parent application. OLE Automation introduces special considerations when naming objects. As a general rule, the expansion of OLE Automation in the '95 toolset has not changed or diminished the value of naming conventions. The following sections discuss naming conventions for your OLE automation code.
Note Visual Basic 4 can now be used to create objects whose only purpose is as an OLE server. Objects in such a server will only be browsed from the Object Browser, and have no interactive use. Thus, you may choose to work extra hard to maximize readability of object names in a such a server.
Table 5 lists entry points for common OLE server applications. Tags to use with objects exposed by these servers are listed in the appropriate sections for each product later in this document.
Table 5. Tags for OLE Object Variables
Object |
Tag |
Access.Application |
accapp |
DAO.DBEngine |
daodbe |
Excel.Application |
xlsapp |
Excel.Chart |
xlscht |
Excel.Sheet |
xlssht |
Graph.Application |
gphapp |
MAPI.Session |
mpsmps |
MSProject.Application |
prjapp |
MSProject.Project |
prjprj |
OfficeBinder.Binder |
bndbnd |
PowerPoint.Application |
pptapp |
SchedulePlus.Application |
scdapp |
SQLOLE.SQLServer |
sqlsvr |
Word.Basic |
wrdbas |
Note that variables for objects in the object hierarchy of a referenced type library can be dimensioned directly by class, as in this line:
Dim xlsapp As Excel.Application
Alternately, if the variable is created with late binding (i.e. as a generic object) rather than early binding, the prefix o is added to denote an object variable:
Dim oxlsapp As Object Set oxlsapp = CreateObject("Excel.Application")
The naming convention for entry points into OLE server applications follows this syntax:
applicationtag [entrypointtag] primaryobjecttag BaseName
The item applicationtag is a three-character notation for the server application, and entrypointtag is three characters denoting the entry point used. The entrypointtag item is optional and should be used when clarification is necessary (when variables for several entry points are declared in the same procedure), or when the entry point is not the standard Application object. The primaryobjecttag describes the ultimate class of the object (the one you intend to address with the variable). The BaseName is optional and clarifies the use of the variable, as with other VBA variables.
For example, the following code creates an Excel Range object and manipulates it.
Sub SalesCheck() Dim xlswksSales As Excel.Worksheet Dim xlsrngYTD As Excel.Range Set xlswksSales = GetObject("C:\Data\Sales.Xls", "Excel.Sheet") Set xlsrngYTD = xlswksSales.Range("YTDSales") If xlsrngYTD.Value < 100000 Then MsgBox "Sales are lame.", vbOKOnly, "Get to Work!" End If Set xlswksSales = Nothing End Sub
In this example, the Range object is technically several layers deep in the application hierarchy, and a purely accurate combination of tags and code structure would yield this line of code, which actually runs:
Set xlsappwkbwksrngYTD = _ xlsapp.ActiveWorkbook.Worksheets("Sales").Range("YTDSales")
In practice, of course, such nomenclature is unwieldy, and the shorter style is accurate yet more friendly.
I prefer to show the server name in the variable declaration for clarity of code. While both lines below will run, the second is much less ambiguous:
Dim xlsrng As Range Dim xlsrng As Excel.Range
In LNC, tags are required for the following Access database objects:
Table 6 lists the tags for Database window objects.
Table 6. Database Window Object Tags
Object |
Tag |
Form |
frm |
Macro |
mcr |
Module |
bas |
Query |
qry |
Report |
rpt |
Table |
tbl |
Do not be lulled into thinking that control tags are superfluous. Some expressions on forms and reports cannot be evaluated when the name of the control is the same as the name of a table field in the object's recordset. For example, if the expression below is used as the ControlSource for a report control this is named Qty in a report whose RecordSource also contains a Qty field, the report will display #Error instead of the proper calculation, due to a "circular reference":
=IIf([Qty]<100,"Low",[Qty])
Table 7 list the tags for control objects on forms and reports. A different tag is provided for each built-in control type, and all control tags are three characters long. VBA code written behind forms and reports using this convention will reflect a control's type in its event procedure names (for example cboState_AfterUpdate). The automatic sorting provided by this notation in the Access module design window can be very helpful during development.
Table 7. Form and Report Control Object Tags
Control |
Tag |
Bound object frame |
frb |
Chart (graph) |
cht |
Check Box |
chk |
Combo box |
cbo |
Command button |
cmd |
Custom control |
ocx |
Image |
img |
Label |
lbl |
Line |
lin |
List box |
lst |
Option button |
opt |
Option group |
grp |
Page break |
brk |
Rectangle |
shp |
Subform/Subreport |
sub |
Text box |
txt |
Toggle button |
tgl |
Unbound object frame |
fru |
VBA variable tags for Access are listed below. Note that the n/a value indicates that the object cannot be assigned to a VBA object variable.
Table 8. Tags for Access VBA Object Variables
Object |
Tag |
Application |
app |
Collection |
col |
Control |
ctl |
Controls |
ctls |
CustomControl |
ocx |
CustomControlInReport |
ocx |
Debug |
n/a |
DoCmd |
doo |
Err |
n/a |
Form |
frm |
Forms |
frms |
GroupLevel |
lvl |
Report |
rpt |
Reports |
rpts |
Screen |
scn |
Section |
sec |
The Excel object model is quite richly featured — as is Excel VBA — providing developers with the ability to program a variety of objects.
The following table shows LNC tags for Excel controls.
Table 9. Excel Control Object Tags
Object |
Tag |
Button |
cmd |
CheckBox/3D |
chk |
EditBox |
edt |
GroupBox |
gbx |
Label |
lbl |
ListBox |
lst |
OptionButton/3D |
opt |
ScrollBar |
sbr |
Spinner |
spn |
TextBox |
txt |
Table 10 lists object tags for variables referring to Excel objects. Collection tags are usually created by adding s to the tag for the corresponding single object, as in arc and arcs. Some objects that are infrequently used do not have tags — you can create object variables for such objects by using the object class as the base name, as in:
Dim xlsAutoCorrect As Excel.AutoCorrect
LNC does not attempt to create tags for infrequently used objects; the table shows none in these instances.
Table 10. Excel Object Tags
Object |
Tag |
AddIn |
add |
AddIns |
adds |
Application |
app |
Arc |
arc |
Arcs |
arcs |
Areas |
ares |
AutoCorrect |
none |
Axis |
axs |
Axes |
axss |
AxisTitle |
none |
Border |
bdr |
Borders |
bdrs |
Button |
cmd |
Buttons |
cmds |
Characters |
none |
Chart |
cht |
Charts |
chts |
ChartArea |
none |
ChartGroup |
chg |
ChartGroups |
chgs |
ChartObject |
cho |
ChartObjects |
chos |
ChartTitle |
none |
CheckBox |
chk |
CheckBoxes |
chks |
Corners |
none |
DataLabel |
dlb |
DataLabels |
dlbs |
Debug |
none |
Dialog |
dlg |
Dialogs |
dlgs |
DialogFrame |
none |
DialogSheet |
dls |
DialogSheets |
dlss |
DocumentProperty |
dcp |
DocumentPropertyies |
dcps |
DownBars |
none |
Drawing |
drw |
Drawings |
drws |
DrawingObjects |
dros |
DropDown |
cbo |
DropDowns |
cbos |
DropLines |
none |
EditBox |
edt |
EditBoxs |
edts |
ErrorBars |
none |
Excel.Application |
xlsapp |
Excel.Chart |
xlscht |
Excel.Sheet |
xlssht |
Floor |
none |
Font |
fnt |
GridLines |
none |
GroupBox |
grp |
GroupBoxes |
grps |
GroupObject |
gro |
GroupObjects |
gros |
HiLoLines |
none |
Interior |
none |
Label |
lbl |
Labels |
lbls |
Legend |
lgd |
LegendEntry |
lges |
LegendEntries |
lges |
LegendKey |
lgk |
Line |
lin |
Lines |
lins |
ListBox |
lst |
ListBoxes |
lsts |
Menu |
mnu |
Menus |
mnus |
MenuBar |
mnb |
MenuBars |
mnbs |
MenuItem |
mni |
MenuItems |
mnis |
Module |
bas |
Modules |
bass |
Name |
nam |
Names |
nams |
Object |
obj |
OLEObject |
ole |
OLEObjects |
oles |
OptionButton |
opt |
OptionButtons |
opts |
Outline |
out |
Oval |
ovl |
Ovals |
ovls |
PageSetup |
none |
Pane |
pan |
Panes |
pans |
Picture |
pic |
Pictures |
pics |
PivotField |
pvf |
PivotFields |
pvfs |
PivotItem |
pvi |
PivotItems |
pvis |
PivotTable |
pvt |
PivotTables |
pvts |
PlotArea |
none |
Point |
pnt |
Points |
pnts |
Range |
rng |
Rectangle |
shp |
Rectangles |
shps |
RoutingSlip |
none |
Scenario |
sce |
Scenarios |
sces |
ScrollBar |
sbr |
ScrollBars |
sbrs |
Series |
ser |
SeriesCollection |
sers |
SeriesLines |
none |
SoundNote |
none |
Spinner |
spn |
Spinners |
spns |
Style |
sty |
Styles |
stys |
TextBox |
txt |
TextBoxes |
txts |
TickLabels |
none |
Toolbar |
tbr |
Toolbars |
tbrs |
ToolbarButton |
btn |
ToolbarButtons |
btns |
Trendline |
tnd |
Trendlines |
tnds |
UpBars |
none |
Walls |
none |
Window |
wnd |
Windows |
wnds |
Workbook |
wkb |
Workbooks |
wkbs |
Worksheet |
wks |
Worksheets |
wkss |
Word has the least-exposed object model among the Microsoft Office suite. However, Word is still programmable without the object model.
The following table shows LNC tags for Word controls.
Table 11. Word Control Object Tags
Object |
Tag |
CancelButton |
cmd |
CheckBox |
chk |
ComboBox |
cbo |
Dialog |
dlg |
FilePreview |
fpvw |
GroupBox |
gbx |
ListBox |
lst |
OKButton |
cmd |
OptionButton |
opt |
Picture |
pic |
PushButton |
cmd |
Text |
lbl |
TextBox |
txt |
Table 12 lists object tags for variables referring to Word objects.
Table 12. Word Object Tags
Object |
Tag |
Basic |
bas |
Word.Basic |
wrdbas |
In addition to object naming conventions, LNC suggests several standardized coding conventions for VBA procedures.
Common coding practices in VBA coding that are supported by LNC include:
There are as many in-line Basic code commenting styles as there are Basic coders. Whatever convention you use, the goals are to be terse yet descriptive, and to be consistent.
LNC suggests placing the following minimum set of comments at the beginning of each procedure:
In addition, we sometimes use these sections in the heading of a procedure:
Some developers like to keep a change log as comments noting all revisions in a procedure. I suggest keeping such comments at the bottom rather than the top, since they are less frequently accessed than the code they displace.
Comments placed on the same line as code should be separated from the code by at least two spaces. Comments placed on their own line should be no longer than 60 characters so they are displayed in full in the default module design view size.
Every procedure that can fail — which is virtually every procedure with more than a few simple lines — should have an error trap. Error traps are created by placing this line at the beginning of the procedure, after the header comments and before any other statements:
On Error GoTo procname_Err
The marker procname should be replaced with the full procedure name. The error handler is placed at the bottom of the procedure, denoted with the label procname_Err:. At the end of the error handler, control is returned somewhere in the procedure, usually to a line label name procname_Exit that precedes a block of code immediately above the error handler.
To allow you to turn off error trapping during program debugging, LNC suggests that you place the On Error statement inside a conditional compilation directive (where supported), like this:
#If pcccDebug Then On Error Goto 0 #Else On Error Goto procname_Err #Endif
Before running an application, you can enable or disable error trapping by setting the value of pcccDebug to -1 (True) or 0 (False) in the "Conditional Compilation Arguments" text box on the Module tab of the Access Options dialog.
Note You can use the Break on All Errors option setting in Access and Excel to achieve a similar result, but the code method shown here is more flexible, since it allows you to add additional functionality to your selective error logic code, such as event logging, and to exempt specific procedures from debugging.
We use the procname_label structure rather than the label_procname structure preferred by many coders to maintain our ObjectVerb construction metaphor as described earlier. Some developers prefer to place the qualifier of the label first, as in Err_procname, but philosophically the phrases Err_, Exit_, and so forth are not class tags, they are qualifiers for the line label object, thus they belong at the end like any other qualifier. This argument becomes more compelling when you remember that you can also create line labels for GoSub and GoTo statements in VBA, and thus creating many different combinations of leading characters, as if they were tags, becomes problematic.
Note In VBA 95, your line labels do not need to be unique, meaning that you can now use Err and Exit as labels in every procedure. LNC, however, continues to prescribe unique labels, which facilitates the use of coding and documentation tools.
You can get the following LNC information and products from Kwery Corporation:
For more information, contact Kwery via the order line at 1-800-ATKWERY, or on the product information line at 425-644-7830. Kwery can also be reached by e-mail and fax at the numbers in the next section.
We welcome your feedback on this document and our conventions, including your likes, dislikes, stories, and suggestions. Please communicate with Kwery Corporation via e-mail at 71573.3261@CompuServe.Com or by fax to 425-644-8409.
This document is provided as is, without warranty of any kind, either express or implied, including but not limited to implied warranties of quality, performance, merchantability, or fitness for any particular purpose.
Some naming convention elements in this document are from the white paper Naming Conventions for Microsoft Access —The Leszynski/Reddick Guidelines for Access 1.x, 2.x, Copyright © 1994 Stan Leszynski and Greg Reddick.
Microrim, Microsoft, Microsoft Access, Microsoft Excel, Microsoft Office, Microsoft PowerPoint, Microsoft Project, Microsoft Schedule Plus, Microsoft SQL Server, Microsoft Visual Basic, Microsoft Visual C++, Microsoft Visual FoxPro, Microsoft Windows, Microsoft Word, Qualitas, and Visual Basic for Applications are trademarks or registered trademarks of their respective owners.
Document Version Number: 95.1.2