0% found this document useful (0 votes)
11 views9 pages

Naming Conventions For Visual Basic

This document outlines naming conventions for Visual Basic programming as recommended by Microsoft Consulting Services. It emphasizes the importance of standardization, readability, and consistency in code naming, including specific prefixes for various object types, variable names, and routines. Additionally, it provides guidelines for code comments, formatting, and the use of Hungarian notation to enhance clarity and maintainability in Visual Basic applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

Naming Conventions For Visual Basic

This document outlines naming conventions for Visual Basic programming as recommended by Microsoft Consulting Services. It emphasizes the importance of standardization, readability, and consistency in code naming, including specific prefixes for various object types, variable names, and routines. Additionally, it provides guidelines for code comments, formatting, and the use of Hungarian notation to enhance clarity and maintainability in Visual Basic applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

NAMING CONVENTIONS FOR VISUAL BASIC

Summary
It is a good idea to establish naming conventions for Visual Basic code. This article provides the
naming conventions used by Microsoft Consulting Services (MCS).

This document is a superset of the coding conventions for Visual Basic found in Visual Basic 'Guide of
programmer.

Note: The third-party controls mentioned in this article are manufactured by independent suppliers of Microsoft.
Microsoft does not grant any warranty, either express or implied, regarding the performance of these controls or reliability.

Development

Naming conventions help Visual Basic programmers:

standardize the structure, style coding, and logic of an application.


create precise, readable and unequivocal code the origin.
be consistent with other language conventions (most importantly, the Visual Basic Programmer's Guide and
Hungarian notation of Windows standard C.
to be efficient from a size of string and labor perspective, thus allowing a greater opportunity for more and more
complete object names.
Define the minimum necessary requirements to carry out the above.

Set the environment options


Use Option Explicit. Declare all variables to store programming time reducing the number of errors.
caused by typographical errors (for example, aUserNameTmp versus sUserNameTmp versus sUserNameTemp). In the box of
dialog Environment options, set the required variable declaration to Yes. The Option Explicit statement requires declaration
todas las variables en el programa de Visual Basic. Guardar archivos como texto ASCII. Guardar formulario (.frm) y módulo (.BAS)
files as ASCII text to facilitate the use of version control systems and minimize the damage that may be due to
damage to the disk. Additionally, it can:

use your own editor


use automated tools, such as grep
create CASE tools or code generation for Visual Basic
perform external analysis of your Visual Basic code
To always save files as ASCII text, from the Visual Basic environment options dialog, set
the option Save as default text format.

Object naming conventions for standard objects


The following tables define the standard object name prefixes of MCS. These prefixes are consistent with the documented ones.
in the Visual Basic Programmer's Guide.
Prefix Object Type Example
-------------------------------------------------------
ani Animation button aniMailBox
bed Bedit Pen bedFirstName
cbo Combo box and drop down list box cboEnglish
chk Checkbox chkReadOnly
clp Picture clip clpToolbar
cmd (3d) Command button (3D) cmdOk (cmd3dOk)
with Communications comFax
ctr Control (when specific type unknown) ctrCurrent
dat Data control datBiblio
dir Directory list box dirSource
dlg Common dialog control dlgFileOpen
drv Drive list box drvTarget
fil File list box filSource
frm Form frmEntry
fra (3d) Frame (3d) fraStyle (fra3dStyle)
gau Gauge gauStatus
gpb Group push button gpbChannel
gra Graph graRevenue
grd Grid grdPrices
hed Pen Hedit hedSignature
hsb Horizontal scroll bar hsbVolume
img Image imgIcon
ink Pen Ink inkMap
key Keyboard key status keyCaps
lbl Label lblHelpMessage
lin Line linVertical
lst List box lstPolicyCodes
mdi MDI child form mdiNote
mpm MAPI message mpmSentMessage
mps MAPI session mpsSession
mci MCI mciVideo
menu Menu File Open
opt (3d) Option Button (3d) optRed (opt3dRed)
ole OLE control oleWorksheet
out Outline control outOrgChart
pic Picture picVGA
pnl3d 3D Panel pnl3d
rpt Report control rptQtr1Earnings
shp Shape controls shpCircle
spn Spin control spnPages
txt Text Box txtLastName
tmr Timer tmrAlarm
vsb Vertical scroll bar vsbRate

Object naming convention for database objects


Prefix Object Type Example
------------------------------------------
db ODBC Database dbAccounts
ds ODBC Dynaset object dsSalesByRegion
fdc Field collection fdcCustomer
fd Field object fdAddress
ix Index object ixAge
ixc Index collection ixcNewAge
qd QueryDef object qdSalesByRegion
qry (suffix) Query (see NOTE) SalesByRegionQry
ss Snapshot object ssForecast
tb Table object tbCustomer
td TableDef object tdCustomers

Note: Using a suffix for queries allows each query to be sorted with its associated table in Microsoft dialogues.
Access (Agregar tabla, lista de tablas instantáneas).

Menu naming conventions


Applications often use an abundance of menu controls. As a result, you need a set of
different naming conventions for these controls. Menu control prefixes must extend beyond the
initial label mnu adding an additional prefix for each level of nesting, with the final menu title at the end of the string
by name. For example:
Menu Caption Sequence Menu Handler Name
[Link] Help Contents
[Link] File Open
[Link] mnuFormatCharacter
[Link] Send Fax
[Link] Send Email

When this convention is used, all members of a certain menu group are displayed together in the object.
dropdown list boxes (from the code window and the properties window). Additionally, the names of menu control
Clearly document the menu items they are connected to.

Naming conventions for other controls


For new controls not listed previously, try to come up with a unique three-character prefix. However, it is more...
important to disable that when sticking to three characters.

For derived controls, such as an enhanced list box, they expand the previous prefixes so there is no confusion about the
control that is actually used. Normally, it will also be added to the prefix of a lowercase abbreviation for the manufacturer.
For example, an instance of the control created from the 3D framework could use Visual Basic Professional with a fra3d prefix to avoid
Confusions about which control is actually used. A command button from MicroHelp could use cmdm to differentiate it.
in the standard command button (cmd).

Third-party controls
Each third-party control used in an application must be listed in the general information comment section.
application, which provides the prefix used for control, the full name of the control and the name of the provider of
software
Prefix Control Type Vendor
cmdm Command Button MicroHelp

Variable and the name of the routine


Variable and function names have the following structure: <prefix><body><qualifier><suffix>
Part Description Example
--------------------------------------------------------------------------
<prefix> Describes the use and scope of the variable. iGetRecordNext
<body> Describes the variable. iGetNameFirst
Denotes a derivative of the variable. iGetNameLast
<suffix> The optional Visual Basic type character. iGetRecordNext%

prefixes:

The following tables define variable and function name prefixes based on Hungarian notation C for Windows. These
prefixes should be used with all variables and function names. Use of basic old suffixes (such as %, &, #, etc.) are
not advisable.

Variable y function name prefixes:


Prefix Converged Variable Use Data Type Suffix
--------------------------------------------------------------------------
b bln Boolean Integer %
c cur Currency - 64 bits Currency @
d dbl Double - 64 bit Double #
signed quantity
dt that Date and Time Variant
e err Error
f sng Float/Single - 32 Single !
signed bit
floating point
h Handle Integer %
i Index Integer %
l lng Long - 32 bit Long &
signed quantity
n int Number/Counter Integer %
s str String String $
u Unsigned - 16 bit Long &
unsigned quantity
udt User-defined type
vnt vnt Variant Variant
a Array

Note: the values in the Converged column represent the efforts to meet the naming standards for Visual Basic.
Visual Basic for Applications and Access Basic. It is likely that these prefixes will become the Microsoft standards in the future.
at some point.

Scope and usage prefixes:


Prefix Description
g Global
m Local to module or form
st Static variable
(no prefix) Non-static variable, prefix local to procedure
v Variable passed by value (local to a routine)
r Variable passed by reference (local to a routine)

Hungarian notation is just as valuable in Visual Basic as in C. Although Visual Basic's type suffixes indicate the data type of a
variable, they do not explain what a variable or function is used for or how it can be accessed. Here are some examples:
iSend - represents a count of the number of messages sent
bSend - A flag to define the success of the last send operation
hSend - an identifier for the communication interface
Indicate each of these variable names to a programmer something very different. This information is lost when the name
The variable reduces to sending %. Scope prefixes like g and m also reduce the name contention problem.
especially in projects with several programmers.

Notación húngara es también muy utilizado por los programadores de C de Windows y hace referencia continuamente en la
Microsoft product documentation and in programming books in the sector. In addition, the bonus among C programmers and
programmers who use Visual Basic will be much stronger like the profit drive of the C++ development system. This
the transition will result in many Visual Basic programmers moving to C for the first time and many programmers with
frequency of moving back and forth between both environments.

The body of the variable and routine names


The body of a variable or the name of a routine must use mixed uppercase and lowercase letters and must be as long as possible.
necessary to describe its purpose. Additionally, function names should start with a verb, such as InitNameArray or
CloseDialog.

For frequently used or long terms, it is recommended to maintain reasonable name lengths in abbreviations.
standard. In general, variable names longer than 32 characters can be difficult to read on VGA screens.

When using abbreviations, ensure they are consistent throughout the application. Randomly switching between number and numeral.
Within a project, unnecessary confusion can arise.

Variable qualifiers and routine names


Related variables and routines are often used to manage and manipulate a common object. In these cases, use qualifiers.
standard for labeling derived variables and routines. Although placing the qualifier after the body of the name can
seem a little complicated (like in sGetNameFirst, sGetNameLast instead of sGetFirstName, sGetLastName) this exercise
will help to list these names together in the Visual Basic editor's routine, making the logic and structure of the application more
easy to understand the order. The following table defines the common qualifiers and their standard meaning:
Qualifier Description (follows Body)
--------------------------------------------------------------------------
First First element of a set.
Last Last element of a set.
Next Next element in a set.
Prev Previous element in a set.
Cur Current element in a set.
Min Minimum value in a set.
Max Maximum value in a set.
Save Used to preserve another variable that must be reset later.
Tmp A "scratch" variable whose scope is highly localized within the
code. The value of a Tmp variable is usually only valid across
a set of contiguous statements within a single procedure.
Src Source. Frequently used in comparison and transfer routines.
Dst Destination. Often used in conjunction with Source.

User-defined types
Declare user-defined types in uppercase with _TYPE appended to the end of the symbol name. For example:
Type CUSTOMER_TYPE
sName As String
sState As String * 2
lID as Long
End Type

when declaring an instance variable of a user, define the type, add a prefix to the variable name for the type of
reference. For example:
Dim custNew as CUSTOMER_TYPE

Nomenclature constants
The body of constant names should be UPPER_CASE with underscores (_) between words. Although constants
Visual Basic standards do not include Hungarian information, prefixes like i, s, g, and m can be very useful for understanding the value and the
scope of a constant. For constant names, they follow the same rules as variables. For example:
Max entry limit for User list (integer value)
local to module
gsNEW_LINE New Line character string (global to entire
application)

Variant data type


If you know that a variable will always store data of a certain type, Visual Basic can manage the data more efficiently if
declare a variable of that type.

However, the variant data type can be very useful when working with databases, messages, DDE, or OLE. Many databases
allow NULL as a valid value for a field. The code needs to distinguish between NULL, 0 (zero), and "" (empty string). Many
Sometimes, these types of operations can use a generic service routine; it is not necessary to know the type of data it receives.
to process or pass in the data. For example:
Sub ConvertNulls(rvntOrg As Variant, rvntSub As Variant)
If rvntOrg = Null, replace the Null with rvntSub
If IsNull(rvntOrg) Then rvntOrg = rvntSub
End Sub
However, there are some drawbacks to using variants. Code instructions that use variants can sometimes be
ambiguous for the programmer. For example:
vnt1 = "10.01" : vnt2 = 11 : vnt3 = "11" : vnt4 = "x4"
vntResult = vnt1 + vnt2 ' Does vntResult = 21.01 or 10.0111?
vntResult = vnt2 + vnt1 ' Does vntResult = 21.01 or 1110.01?
vntResult = vnt1 + vnt3 ' Does vntResult = 21.01 or 10.0111?
vntResult = vnt3 + vnt1 ' Does vntResult = 21.01 or 1110.01?
vntResult = vnt2 + vnt4 ' Does vntResult = 11x4 or ERROR?
vntResult = vnt3 + vnt4 ' Does vntResult = 11x4 or ERROR?

the previous examples would be much less ambiguous and easier to read, debug, and maintain if the type conversion routines
Visual Basic was used instead. For example:
iVar1 = 5 + val(sVar2) use this (explicit conversion)
vntVar1 = 5 + vntVar2 not this (implicit conversion)

Code comments
All procedures and functions must begin with a brief comment describing the functional characteristics of the
routine (what it does). This description should describe not the implementation details (how it does it) because these usually
they change over time, the maintenance work of unnecessary comments or worse yet, erroneous comments. The own
Code and the necessary inline or local comments describe the implementation.

Parameters passed to a routine should be described when their functions are not obvious and when the routine expects the parameters.
in a specific interval. Function returns values and global variables that have changed by the routine (especially through
The reference parameters must also be described at the beginning of each routine.

Header comment routine should look for blocks like this (see the next section 'Format the code' for more information)
an example):
Section Comment Description
--------------------------------------------------------------------------
Purpose What the routine does (not how).
Inputs Each non-obvious parameter on a separate line with
in-line comments
Assumes List of each non-obvious external variable, control, open file,
and so on.
Returns Explanation of value returned for functions.
Effects List of each affected external variable, control, file, and
so on and the effect it has (only if this is not obvious)

Each non-trivial variable declaration must include an inline comment describing the use of the declared variable.

Variables, controls, and routines should have a name clear enough that inline comments are only necessary
for details of complex or non-intuitive implementation.

A description of general information about the application, listing main data objects, routines, and algorithms, tables of.
dialogue, database, and system dependency file, and so on must be included at the beginning of the .BAS module.
which contains generic constant declarations of the Visual Basic project.

Note: The project window intrinsically describes the list of files in a project, so this section of information
In general, only information about the modules and the most important files or the files that do not display is needed.
ventana proyecto, como archivos de base de datos o de inicialización (ini).

The format code


Since many programmers still use VGA display, screen real estate should be saved as much as possible but
allowing format to reflect the logical structure and nesting of code.

Standard block, based on a card, the indentations for nesting should be two to four spaces. More than four spaces are unnecessary and
It can make the instructions hidden or accidentally truncated. Less than two spaces does not display sufficiently.
logical nesting. In Microsoft Knowledge Base, we use a three-space indentation. Use the Options dialog
environment to set the default card width.

The functional introduction comment of a routine should be an indentation space. The higher-level instructions that follow it
The introduction comment should be a card with indentation, with each nested block applying indentation to an additional card. For
example:
**************************************************************************
Purpose: Locate first occurrence of a specified user in UserList array.
Inputs: rasUserList(): the list of users to be searched
' rsTargetUser: the name of the user to search for
Returns: the index of the first occurrence of the rsTargetUser
' in the rasUserList array. If target user not found, return -1.
'**************************************************************************

VB3Line: Enter the following lines as one line


Function iFindUser (rasUserList() As String, rsTargetUser as String) _
As Integer
Dim i As Integer loop counter
Dim bFound As Integer target found flag
iFindUser = -1
i=0
While i <= Ubound(rasUserList) and Not bFound
If rasUserList(i) = rsTargetUser Then
bFound = True
iFindUser = i
End If
Wend
End Function

Non-generic variables and constants should be grouped by function rather than by going to deactivate isolated areas or
special files. Generic constants in Visual Basic such as the ARENA clock should be grouped in a single module (VB_STD.BAS)
to keep them independent of specific application statements.

Operators
Always use an ampersand (&) when concatenating strings and the plus sign (+) when working with numeric values. With a sign
more (+) with non-numeric values can cause problems when it operates in both variants. For example:
vntVar1 = "10.01"
vntVar2 = 11
vntResult = vntVar1 + vntVar2 ' vntResult = 21.01
vntResult = vntVar1 & vntVar2 ' vntResult = 10.0111

Scope
Variables should always be defined with the smallest possible scope. Global variables can create state machines.
immensely complex and implement the logic of an extremely difficult-to-understand application. Global variables also that
the reuse and maintenance of your code much more difficult. Variables in Visual Basic can have the following scope:
Scope Variable Declared In: Visibility
--------------------------------------------------------------------------
Procedure-level Event procedure, sub, or Visible in the
function procedure in which
it is declared
Form-level, Declarations section of a form Visible in every
Module-level or code module (.FRM, .BAS) procedure in the
form or code
module
Global Declarations section of a code Always visible
module (.BAS, using Global
keyword

In a Visual Basic application, only use global variables when there is no other convenient way to share data.
between forms. You may want to store information in the control's tag property, which can have global access.
through the syntax [Link].

If global variables must be used, it is advisable to declare all of them in a single module and group them by function. Assign the module
give it a meaningful name that indicates its purpose, like [Link].

With the exception of variables (which should not be passed), procedures and global functions should only work with objects that are
They are passed to them. Global variables used in the routines must be identified in the general comment area at the beginning of the
routine. In addition, pass arguments to subroutines and functions by ByVal, unless you explicitly want to change the value of
past argument.

Write modular code whenever possible. For example, if the application displays a dialog, place all the
controles y código necesario para realizar tareas del cuadro de diálogo en un solo formulario. Esto ayuda a mantener el código de la
application organized into useful components and reduces its runtime overhead.

Third-party controls
Note: The products described below are manufactured by independent suppliers of Microsoft. Microsoft does not
provides no warranty, either implied or otherwise, regarding the performance or reliability of these products.

The following table shows standard third-party vendor prefix characters to be used with control prefixes:
Vendor Abbv
-------------------------

MicroHelp (VBTools) m
Pioneer Software p
Crescent Software c
Sheridan Software s
Other (Misc) o

The following table shows the standard third-party control prefixes:


Control Control Abbr Vendor Example VBX File
Type Name Name
--------------------------------------------------------------------------
Alarm Alarm almm MicroHelp almmAlarm [Link]
Animate Animate anim MicroHelp animAnimate [Link]
Callback Callback calm MicroHelp calmCallback [Link]
Combo Box DB_Combo cbop Pioneer cbopComboBox [Link]
Combo Box SSCombo Cbos Sheridan cbosComboBox [Link]
Check Box DB_Check chkp Pioneer chkpCheckBox [Link]
Chart Chart chtm MicroHelp chtmChart [Link]
Clock Clock clkm MicroHelp clkmClock [Link]
Button Command cmdm MicroHelp cmdmCommandButton [Link]
Button
Button DB_Command cmdp Pioneer cmdpCommandButton [Link]
Button (Group) Command cmgm MicroHelp cmgmBtton [Link]
Button
(multiple)
Button Command cmim MicroHelp cmimCommandButton [Link]
Button
(icon)
CardDeck CardDeck crdm MicroHelp crdmCard [Link]
Die Dice dicm MicroHelp dicmDice [Link]
List Box (Dir) SSDir dirs Sheridan dirsDirList [Link]
List Box (Drv) SSDrive drvs Sheridan drvsDriveList [Link]
List Box (File) File List film MicroHelp filmFileList [Link]
List Box (File) SSFile son Sheridan fileList [Link]
Flip Flip flpm MicroHelp flpmButton [Link]
Scroll Bar Form Scroll fsrm MicroHelp fsrmFormScroll ???
Gauge Gauge gagm MicroHelp gagmGauge [Link]
Graph Graph gpho Other gphoGraph [Link]
Grid Q_Grid grdp Pioneer grdpGrid [Link]
Scroll Bar Horizontal hsbm MicroHelp hsbmScroll [Link]
Scroll Bar
Scroll Bar DB_HScroll hsbp Pioneer hsbpScroll [Link]
Graph History hstm MicroHelp hstmHistograph [Link]
Invisible Invisible invm MicroHelp invmInvisible [Link]
List Box Icon Tag itgm MicroHelp itgmListBox [Link]
Key State Key State kstm MicroHelp kstmKeyState [Link]
Label Label (3d) lblm MicroHelp lblmLabel [Link]
Line Line linm MicroHelp linmLine [Link]
List Box DB_List lstp Pioneer lstpListBox [Link]
List Box SSList lsts Sheridan lstsListBox [Link]
MDI Child MDI Control mdcm MicroHelp mdcmMDIChild ???
Menu SSMenu Sheridan mnusMenu [Link]
Brand Brand mrqm MicroHelp mrqmBrand [Link]
Picture OddPic odpm MicroHelp odpmPicture [Link]
Picture Picture picm MicroHelp picmPicture [Link]
Picture DB_Picture picp Pioneer picpPicture [Link]
Property Vwr Property pvrm MicroHelp pvrmPropertyViewer [Link]
Viewer
Option (Group) DB_RadioGroup radp Pioneer radqRadioGroup [Link]
Slider Slider sldm MicroHelp sldmSlider [Link]
Button (Spin) Spinner spnm MicroHelp spnmSpinner [Link]
Spreadsheet Spreadsheet sprm MicroHelp sprmSpreadsheet [Link]
Picture Stretcher strm MicroHelp strmStretcher [Link]
Screen Saver Screen Saver svrm MicroHelp svrmSaver [Link]
Switcher Switcher swtm MicroHelp swtmSwitcher ???
List Box Tag tagm MicroHelp tagmListBox [Link]
Timer Timer tmrm MicroHelp tmrmTimer [Link]
ToolBar ToolBar MicroHelp ToolBar [Link]
List Box Tree trem MicroHelp tremTree [Link]
Input Box Input (Text) txtm MicroHelp inpmText [Link]
Input Box DB_Text txtp Pioneer txtpText [Link]
Scroll Bar Vertical vsbm MicroHelp vsbmScroll [Link]
Scroll Bar
Scroll Bar DB_VScroll vsbp Pioneer vsbpScroll [Link]

Source:[Link]

You might also like