STANDARD
Visual Basic Coding Convention
Code 09fe-HD/PM/HDCV/FSOFT
Version 1/1
Effective date 10/Jun/2013
Standard_Visual Basic Coding Convention V1/1
RECORD OF CHANGE
*A - Added M - Modified D – Deleted
Effective Changed Items A* Change Description New
Date M, D Version
10/06/13 3.1.1 Modules M Updated name and filename of V1/1
"MDI form ", "MDI child form",
"Modal dialog box"
10/06/13 3.1.2 Suggested M Update Prefix and Example of "MS V1/1
Prefixes for Flex grid, Vertical scroll bar"
Controls
10/06/13 3.1.3 Suggested A added new "File Send Fax, Format V1/1
Prefixes for Menus Character, Help Contents"
10/06/13 3.1.5 Creation M Update Example of "Global, V1/1
Variable Names Module-level"
10/06/13 3.1.7 Constant A,M Added new ". Although standard V1/1
Visual Basic constants do not
include Hungarian information,
prefixes like int, str,g and m can be
very useful in understanding the
value and scope of a constant. For
constant names, follow the same
rules as variables"; Updates
Example "Public Const
gstrDATE_FORMAT as String =
“DD/MM/YYYY”
09fe-HD/PM/HDCV/FSOFT 2/26
Standard_Visual Basic Coding Convention V1/1
TABLE OF CONTENTS
Record of change ................................................................................................................... 2
1. INTRODUCTION........................................................................................................... 5
1.1. Purpose ........................................................................................................................ 5
1.2. Application scope .......................................................................................................... 5
1.3. Related documents ....................................................................................................... 5
1.4. Definition ....................................................................................................................... 5
2. GENERAL .................................................................................................................... 6
2.1. Source for the Coding Convention ................................................................................. 6
2.2. Structure of the Coding Convention ............................................................................... 6
3. DETAIL ......................................................................................................................... 7
3.1. Naming Convention ....................................................................................................... 7
3.1.1. Modules ........................................................................................................................ 7
3.1.2. Suggested Prefixes for Controls .................................................................................... 7
3.1.3. Suggested Prefixes for Menus ..................................................................................... 11
3.1.4. Choosing Prefixes for Other Controls........................................................................... 11
3.1.5. Creation Variable Names............................................................................................. 12
3.1.6. User-Defined Types .................................................................................................... 14
3.1.7. Constant ..................................................................................................................... 14
3.2. Code Commenting Conventions .................................................................................. 14
3.2.1. Procedure and function header comment .................................................................... 14
3.2.2. Inline comment ............................................................................................................ 15
3.3. Spacing, formatting, and indenting............................................................................... 16
3.3.1. Indenting ..................................................................................................................... 16
3.3.2. Grouping Constants .................................................................................................... 16
3.3.3. & and + Operators ....................................................................................................... 17
3.4. Form Layout ................................................................................................................ 17
3.5. Report Layout ............................................................................................................. 18
3.5.1. Common conventions in report design ......................................................................... 18
3.5.2. Report objects appearance conventions ...................................................................... 18
4. DATABASE ................................................................................................................ 21
5. ERROR HANDLING ................................................................................................... 22
09fe-HD/PM/HDCV/FSOFT 3/26
Standard_Visual Basic Coding Convention V1/1
6. TIP .............................................................................................................................. 23
6.1. Enum Types and type checking ................................................................................... 23
6.2. Checklist ..................................................................................................................... 23
6.3. Conversion strings into decimal (Single of Double) ...................................................... 24
6.3.1. Val() function .............................................................................................................. 24
6.3.2. CSng() and CDbl() functions ........................................................................................ 24
6.4. Multital……………………………………………………………………………………………25
6.5. DLL’s and OCX’s ......................................................................................................... 25
09fe-HD/PM/HDCV/FSOFT 4/26
Standard: Visual Basic Coding Convention V1/1
1. INTRODUCTION
1.1. Purpose
Purpose of this document is to provide Coding Convention for all developers in all Visual Basic
projects for our group.
The main reason for using a consistent set of coding conventions is to standardize the
structure and coding style of an application so that you and others can easily read and
understand the code.
Good coding conventions result in precise, readable, and unambiguous source code that is
consistent with other language conventions and as intuitive as possible.
1.2. Application scope
Fsoft projects
1.3. Related documents
No. Code Name of documents
1 04e-QT/PM/HDCV/FSOFT Process_Coding
1.4. Definition
Terminology Explanation
VB Visual Basic
09fe-HD/PM/HDCV/FSOFT 5/26
Standard_Visual Basic Coding Convention V1/1
2. GENERAL
2.1. Source for the Coding Convention
This document is made from Coding Convention of Microsoft Visual Basic
2.2. Structure of the Coding Convention
- Naming conventions for objects, variables, and procedures.
- Standardized formats for labeling and commenting code.
- Guidelines for spacing, formatting, and indenting.
09fe-HD/PM/HDCV/FSOFT 6/26
Standard_Visual Basic Coding Convention V1/1
3. DETAIL
3.1. Naming Convention
3.1.1. Modules
Type module Name Filename
Project SSTNNXX <root>\[Link]
MDI form frmMain <root>\[Link]
MDI child form mdiXxxYyy <root>\[Link]
Modal dialog box dlgXxxYyy <root>\[Link]
Class CXxxYyy <root>\[Link]
Interface IXxxYyy <root>\IxxxYyy
Code module XxxYyy <root>\[Link]
Package IDX_xxxx
Where XxxYyy = a functional describing name
<root> = the root directory for source code
SSTNN = application name, module code...
3.1.2. Suggested Prefixes for Controls
Control type Prefix Example
3D Panel pnl pnlGroup
ADO Data ado adoBiblio
Animated button ani aniMailBox
Check box chk chkReadOnly
Combo box, drop-down list cbo cboEnglish
box
Command button cmd cmdExit
Common dialog dlg dlgFileOpen
09fe-HD/PM/HDCV/FSOFT 7/26
Standard_Visual Basic Coding Convention V1/1
Control type Prefix Example
Communications com comFax
Control (used within ctr ctrCurrent
procedures when the
specific type is unknown)
Data dat datBiblio
Data-bound combo box dbcbo dbcboLanguage
Data-bound grid dbgrd dbgrdQueryResult
Data-bound list box dblst dblstJobType
Data combo dbc dbcAuthor
Data grid dgd dgdTitles
Data list dbl dblPublisher
Data repeater drp drpLocation
Date picker dtp dtpPublished
Directory list box dir dirSource
Drive list box drv drvTarget
File list box fil filSource
Flat scroll bar fsb fsbMove
Form frm frmEntry
Frame fra fraLanguage
Gauge gau gauStatus
Graph gra graRevenue
Grid grd grdPrices
09fe-HD/PM/HDCV/FSOFT 8/26
Standard_Visual Basic Coding Convention V1/1
Control type Prefix Example
Hierarchical flexgrid flex flexOrders
Horizontal scroll bar hsb hsbVolume
Image img imgIcon
Image combo imgcbo imgcboProduct
ImageList ils ilsAllIcons
Label lbl lblHelpMessage
Lightweight check box lwchk lwchkArchive
Lightweight combo box lwcbo lwcboGerman
Lightweight command lwcmd lwcmdRemove
button
Lightweight frame lwfra lwfraSaveOptions
Lightweight horizontal scroll lwhsb lwhsbVolume
bar
Lightweight list box lwlst lwlstCostCenters
Lightweight option button lwopt lwoptIncomeLevel
Lightweight text box lwtxt lwoptStreet
Lightweight vertical scroll lwvsb lwvsbYear
bar
Line lin linVertical
List box lst lstPolicyCodes
ListView lvw lvwHeadings
MAPI message mpm mpmSentMessage
09fe-HD/PM/HDCV/FSOFT 9/26
Standard_Visual Basic Coding Convention V1/1
Control type Prefix Example
MAPI session mps mpsSession
MCI mci mciVideo
Menu mnu mnuFileOpen
Month view mvw mvwPeriod
MS Chart ch chSalesbyRegion
MS Flex grid msg msgClients
MS Tab mst mstFirst
OLE container ole oleWorksheet
Option button opt optGender
Picture box pic picVGA
Picture clip clp clpToolbar
ProgressBar prg prgLoadFile
Remote Data rd rdTitles
RichTextBox rtf rtfReport
Shape shp shpCircle
Slider sld sldScale
Spin spn spnPages
StatusBar sta staDateTime
SysInfo sys sysMonitor
TabStrip tab tabOptions
Text box txt txtLastName
09fe-HD/PM/HDCV/FSOFT 10/26
Standard_Visual Basic Coding Convention V1/1
Control type Prefix Example
Timer tmr tmrAlarm
Toolbar tlb tlbActions
TreeView tre treOrganization
UpDown upd updDirection
Vertical scroll bar vsb vsbRate
3.1.3. Suggested Prefixes for Menus
Applications frequently use many menu controls, making it useful to have a unique set of
naming conventions for these controls. Menu control prefixes should be extended beyond the
initial "mnu" label by adding an additional prefix for each level of nesting, with the final menu
caption at the end of the name string. The following table lists some examples.
Menu caption sequence Menu handler name
File Open mnuFileOpen
File Send Email mnuFileSendEmail
File Send Fax mnuFileSendFax
Format Character mnuFormatCharacter
Help Contents mnuHelpContents
3.1.4. Choosing Prefixes for Other Controls
For controls not listed above, you should try to standardize on a unique two or three character
prefix for consistency. Use more than three characters only if needed for clarity.
For derived or modified controls, for example, extend the prefixes above so that there is no
confusion over which control is really being used. For third-party controls, a lower-case
abbreviation for the manufacturer could be added to the prefix. For example, a control instance
created from the Visual Basic Professional 3D frame could uses a prefix of fra3d to avoid
confusion over which control is really being used.
09fe-HD/PM/HDCV/FSOFT 11/26
Standard_Visual Basic Coding Convention V1/1
3.1.5. Creation Variable Names
Variables are conceived as follows : s_dddXxxYyy
where s = profix according scope
ddd = prefix according datatype
XxxYyy = functional designation
Prefixes that are added by Visual basic are not changed( although possible) f.i. when one uses
the class wizard to add a property blnIsBezig a private variable is generated with the name
mvarblnIsBezig.
a. Variable Scope Prefixes
Scope Prefix Example
Global g gstrUserName
Module-level m mblnCalcInProgress
Local to procedure None dblVelocity
Argument a (an) a_strUserName
an_objTarget
(*) “an” is used when the next character is a vowel, in order to avoid that the two vowels are
used together. Also with wordt consonants such as “m” and “n”, which are pronounced as if
the would start with a vowel.
b. Variable Data Types
Data type Prefix Example
Boolean Bln blnFound
Byte Byt bytRasterData
Collection object Col colWidgets
Currency Cur curRevenue
Date (Time) Dtm dtmStart
Double Dbl dblTolerance
Error Err errOrderNum
09fe-HD/PM/HDCV/FSOFT 12/26
Standard_Visual Basic Coding Convention V1/1
Data type Prefix Example
Integer Int intQuantity
Long Lng lngDistance
Object Obj objCurrent
Single Sng sngAverage
String Str strFName
User-defined type Udt udtEmployee
Variant Vnt vntCheckSum
ADO Command C cCustomers
ADO Connection Conn connActive
ADO RecordSet Rs rsCustomers
ADO Field Fld fldAmount
ADO Parameter Par parAmount
Remark : for user-defined class it is better to use an instance variable with a name
corresponding with the class. f.i.:
Dim objTarief as CTarief
Dim objKasbonPlus as CKasbonPlus
c. Descriptive Functions, procedures, methods… Names
format : WwwXxxYyy
where Www = a verb
XxxYyy = one or more describing terms
Examples :
- OphalenBoekingen or OhlBk
- OpvullenScherm or OvlSrm
Verbs are always written in the infinitive
09fe-HD/PM/HDCV/FSOFT 13/26
Standard_Visual Basic Coding Convention V1/1
The body of procedure or function name should use mixed case and should be as long as
necessary to describe its purpose. In addition, function names should begin with a verb, such
as InitNameArray or CloseDialog.
For frequently used or long terms, standard abbreviations are recommended to help keep
name lengths reasonable. In general, variable names greater than 32 characters can be
difficult to read on VGA displays.
When using abbreviations, make sure they are consistent throughout the entire application.
Randomly switching between Cnt and Count within a project will lead to unnecessary
confusion.
Calling up a procedure or function from another module results into an indication in the
modulename:
Dim strPerNr as String
strPerNr = [Link](39868, 1);
Dim strPersoneelsNummer as String
strPersoneelsNummer = [Link](39868, 1);
3.1.6. User-Defined Types
In a large project with many user-defined types, it is often useful to give each such type a
three-character prefix of its own. If these prefixes begin with "u," they will still be easy to
recognize quickly when you are working with a user-defined type. For example, “ucli” could be
used as the prefix for variables of a user-defined Client type.
3.1.7. Constant
Must be UPPER CASE and has a underscore (_) between each word. Although standard
Visual Basic constants do not include Hungarian information, prefixes like int, str,g and m can
be very useful in understanding the value and scope of a constant. For constant names, follow
the same rules as variables.
For Example: Public Const gstrDATE_FORMAT as String = “DD/MM/YYYY”
3.2. Code Commenting Conventions
3.2.1. Procedure and function header comment
All procedures and functions should begin with a brief comment describing the functional
characteristics of the procedure (what it does). This description should not describe the
implementation details (how it does it) because these often change over time, resulting in
unnecessary comment maintenance work, or worse yet, erroneous comments. The code itself
and any necessary inline comments will describe the implementation.
09fe-HD/PM/HDCV/FSOFT 14/26
Standard_Visual Basic Coding Convention V1/1
Arguments passed to a procedure should be described when their functions are not obvious
and when the procedure expects the arguments to be in a specific range. Function return
values and global variables that are changed by the procedure, especially through reference
arguments, must also be described at the beginning of each procedure.
Procedure header comment blocks should include the following section headings.
Section heading Comment description
Purpose What the procedure does (not how).
Inputs Each argument that may not be obvious. Arguments are on a
separate line with inline comments.
Returns Explanation of the values returned by functions.
Author Name and Office
For example:
'********************************************************************
' Purpose: Adds a new user into the database
' Inputs:
' strLoginName : LoginName of User to identify another user
' strPassword: Password of user to use
' blnFlagFirstLogin: The value for identify user login into
system in the first time
' Returns:
' True value if insert into database completed success
' False value if insert into database not completed
' Author: Nguyen Van A – Developer, Group X, FPT-SOFT
'********************************************************************
3.2.2. Inline comment
Code has to be below its comment.
Remember the following points:
- Every important variable declaration should include an inline comment describing the
use of the variable being declared.
- Variables, controls, and procedures should be named clearly enough that inline
commenting is only needed for complex implementation details.
09fe-HD/PM/HDCV/FSOFT 15/26
Standard_Visual Basic Coding Convention V1/1
- At the start of the .bas module that contains the project's Visual Basic generic constant
declarations, you should include an overview that describes the application, enumerating
primary data objects, procedures, algorithms, dialogs, databases, and system
dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful.
Example
’ Variable is used to keep status of program
Dim intStatus as Integer
3.3. Spacing, formatting, and indenting
3.3.1. Indenting
Standard, tab-based, nested blocks should be indented, and converted to four spaces
The functional overview comment of a procedure should be indented one space. The highest
level statements that follow the overview comment should be indented one tab, with each
nested block indented an additional tab.
Example:
Function FindUser (strUserList() As String, _
strTargetUser As String)As Integer
' Loop counter.
Dim i As Integer
' Target found flag.
Dim blnFound As Boolean
FindUser = -1
i = 0
While i <= Ubound(strUserList) and Not blnFound
If strUserList(i) = strTargetUser Then
blnFound = True
intFindUser = i
End If
i = i + 1
Wend
End Function
3.3.2. Grouping Constants
Variables and defined constants should be grouped by function rather than split into isolated
areas or special files. Visual Basic generic constants should be grouped in a single module to
separate them from application-specific declarations.
09fe-HD/PM/HDCV/FSOFT 16/26
Standard_Visual Basic Coding Convention V1/1
3.3.3. & and + Operators
Always use the & operator when linking strings and the + operator when working with
numerical values. Using the + operator to concatenate may cause problems when operating
on two variants. For example:
vntVar1 = "10.01"
vntVar2 = 11
vntResult = vntVar1 + vntVar2 'vntResult = 21.01
vntResult = vntVar1 & vntVar2 'vntResult = 10.0111
3.4. Form Layout
Item Value Example
Button height 375
Button width Normally should be: 1095
Order of buttons on screen Left
Font style on screen (Apply Tahoma
to all controls)
Font size on screen (Apply to 8
all controls)
Form Controls alignment left
Font color for buttons Black (default)
Background color for button &H8000000F (Default)
Default button Must be set
Cancel button Must be set
Button alignment on a form Left
Tab order Must be set
Alignment on fields Date: Centered
Numeric: Right
String: Left
Shortcut for controls on form Must be defined
The distance between 1 column (in design mode)
buttons
09fe-HD/PM/HDCV/FSOFT 17/26
Standard_Visual Basic Coding Convention V1/1
Item Value Example
The width of buttons on 1 Should be the same
form
Height of text box 315
Height of Combo box 315
Colon sign after label
Bottom margin?
Labels Should have name
Date DD/MM/YYYY
Grid units 60 x 60 twips
3.5. Report Layout
3.5.1. Common conventions in report design
Items Conventions Note
Above of each total row must be a line,
called Grouping line
Report border None
Color of all objects in report (line, Black
character...)
3.5.2. Report objects appearance conventions
Object Property Setting Note
Report title
Font name Arial MS P ゴシック for
Japanese
Font style Bold
Justify Left
Size 16
Column
heading
Font name Arial MS P ゴシック for
09fe-HD/PM/HDCV/FSOFT 18/26
Standard_Visual Basic Coding Convention V1/1
Object Property Setting Note
Japanese
Font style Bold
Font size 10
Justify Column left
Before row spacing 6 Points
After row spacing 6 Points
Report body
(data)
Font name Arial MS P ゴシック for
Japanese
Font style Regular
Font size 9
Justify Depend on column
data type
(Number: right,
string: right, date:
center)
Row spacing 0
Total row
Font name Arial MS P ゴシック for
Japanese
Font style Bold
Font size 9
Justify Right
Position Under data block
that summarized
Grouping line
Width 1 Point
Report border None
09fe-HD/PM/HDCV/FSOFT 19/26
Standard_Visual Basic Coding Convention V1/1
Object Property Setting Note
Page number
Font name Time News MS P ゴシック for
Roman Japanese
Font size 9
Font style Normal
Position Right, bottom of
page (Report
footer)
Style
Left sub title
Font name Arial MS P ゴシック for
Japanese
Font size 10
Font style Normal
Justify Margin left
Right sub title
Font name Arial MS P ゴシック for
Japanese
Font size 10
Font style Normal
09fe-HD/PM/HDCV/FSOFT 20/26
Standard_Visual Basic Coding Convention V1/1
4. DATABASE
Microsoft ActiveX Data Objects 2.5 Library as middleware.
Use [Link] Objects for SQL statements (see also examples).
Use Parameters for variables in the SQL – never compose a SQL statement by concatenating
the variable values in the SQL string.
To complete a recordset, use [Link] method. Don’t use [Link] .
Use Bookmarks to keep track of a selection a user previously made in e.g. a grid.
Restrict Recordsets to a number of rows .
Use as much as possible read-only for Recordsets. If you have many records in a list, and
you need to edite, you can always open a separate Recordset with only one Record.
After an action on a selected row in a grid (f.i. by using a Bookmark), you can maintain the
same selection Create Recordsets with a minimum of locking.
Use Excel and Word 2000.
For Access, Use “[Link] = adUseClient” Explicitly.
Reason:
Recordset cursors are client-side unless the performable profit of server-side cursors is
considerable. Problems arise with Jet4.0 oledb driver when server-side cursors are used (see
msdn “PRB: DataGrid Not Populated Using [Link].4.0 Provider and ADO Server Side
Cursor”).
09fe-HD/PM/HDCV/FSOFT 21/26
Standard_Visual Basic Coding Convention V1/1
5. ERROR HANDLING
All event handlers have an error handler. If this isn’t provided and a error appears, the
application will be closed by VB (!).
Good programming practice: only one error handler in all procedures. In some cases this will
be superfluous.
Error will be raised and sent to form. Error will be logged at the class level.
[Link] messages for unexpected errors are hard coded ;
[Link] messages for functional errors (i.e. the errors we expect to get, e.g. invalid
input by user) are generated at runtime by using the message manager. These messages can
be parameterized to pass context sensitive information and can be shown directly by the
presentation layer.
Unexpected errors should be written to the application’s log file;
Be careful when using message boxes:
Only forms can contain message boxes
Never use them in class modules
Never use them in any kind of loops
Put as few code into the class_Initialize event as possible. The object isn’t really created yet at
that point which makes error handling less evident.
Create an extra “Initialize” method which can be called after creating the logger and other
utility classes.
Do not use On Error Resume Next.
09fe-HD/PM/HDCV/FSOFT 22/26
Standard_Visual Basic Coding Convention V1/1
6. TIP
6.1. Enum Types and type checking
By using variables of the type enumeration it isn’t guaranted that the variables of this type are
limited to the values defined by the enrum type.
Public Enum eAlignment
Left = 1
Center = 2
Right = 4
Full = 8
End Enum
……..
Public Property Alignment(an_Alignment As eAlignment)
m_Alignment = an_Alignment
End Property
….
[Link] = 456
Above-metioned line is executed, without causing an error. The value is accorded to the
variable m_Alignment, unless the programmer himself examines if the mentioned value is
found within the means.
In other words Enum types verify the datatype, but not if the value belongs to the defined
values within the enum type.
6.2. Checklist
1 ByVal Explicitly indicate Parameters. ByRef avoid Parameters
2 ByRef Parameters are not advised d for input/output. If it seems necessary, a class
is probably a better solution.
3 Use Option Explicit in all modules
4 Use Option Base 0 in all modules
5 Install Auto-increment version numbers in Project Properties
6 Use blank lines to organize a code in logical matching blocs.
7 Use enumerations (enum) for possible values of function and sub parameters.
8 If you open sub procedures, never use brackes for argument(s)
09fe-HD/PM/HDCV/FSOFT 23/26
Standard_Visual Basic Coding Convention V1/1
9 Never use default properties.
f.i., strNaam = [Link] i.p.o. strNaam = txtNaam
10 Methods and classes are saved in the “Attributes – Description” panel in the
classbuilder. This description can be found in the Object browser.
11 Don’t use broad variables. (OK, perhaps one or two).
12 Use Module level variables only when necessary (property values, …). Don’t use it
for communication between subroutines.
13 Always use IF
Then
End If
6.3. Conversion strings into decimal (Single of Double)
6.3.1. Val() function
Problem : System operates independent from Regional settings Windows.
Example :
Dim sngBedrag as Single
sngBedrag = Val([Link])
Result :
Decimal separator in String in Waarde sngBedrag
Windows [Link]
Comma 123.45 123,45
Comma 123,45 123,0 x
Period 123.45 123,45
Period 123,45 123,0 x
Conclusion :
Don’t use this function with amounts, except in exceptional circumstances where the operation
can’t cause problemes.
6.3.2. CSng() and CDbl() functions
Problem : These functions depent on the Regional settings Windows, but operate incorrect if
the string, that needs to be converted, has a different format than the international settings.
09fe-HD/PM/HDCV/FSOFT 24/26
Standard_Visual Basic Coding Convention V1/1
If the decimal and thousand separator are switched (f.i. English into Dutch), no fault is raised.
The symbol that the user applies as decimal, is considered and ignored as thousand
separator.
Example :
Dim sngBedrag as Single
sngBedrag = CSng([Link])
Result :
Decimal separator in Waarde [Link] Waarde sngBedrag
Windows
Comma 123.45 12345,0 x
Comma 123,45 123,45
Period 123.45 123,45
Period 123,45 12345,0 x
Conclusion :
The developer needs to know for sure that the correct decimal separator is used in the
convertable string. f.i. don’t use wrong symbols in the textbox.
6.4. Multital
To do this… Do this..
Multitaal [Link] Install an invisible label on the form and add it in the
translationdatabase.
In the label change event, put [Link] = [Link]
6.5. DLL’s and OCX’s
- Most of the applications won’t require separate DLL’s.
- OCX’s are not evident and need to be used carefully.
You always unregister all un-used DLL’s before deleting the DDL of the developing PC.
09fe-HD/PM/HDCV/FSOFT 25/26
Standard_Visual Basic Coding Convention V1/1
Approver Reviewer Creator
Nguyen Quang Hoa Vu Tuan Manh Le Kha Tuan
09fe-HD/PM/HDCV/FSOFT 26/26