1. "&" replaces "+"
2. Variable naming should be case-sensitive, statements should be well-organized, and source code maintenance should be done
3. Please develop the following good habits of "object naming convention"
4. In the case of simple selection conditions, use the IIf() function
5. Try to use Debug.Print for debugging
6. When repeatedly modifying the properties of an object, try to use With....End With
7. Try to use message icons in MsgBox so that the program is more standardized. 8. Use enumerations when possible.
1. "&" replaces "+"
In many people's programming languages, "+" is used to connect strings, which can easily lead to ambiguity. A good practice is to use "&" to concatenate strings.
Incorrect:
Dim sMessage As String
sMessage = "1" + "2"
correct:
Dim sMessage As String
sMessage = "1" & "2"
Note: There is a space after "&"
2. Variable naming should be case-sensitive, statements should be well-organized, and source code maintenance should be done
Let’s compare the following two pieces of code:
Read difficult code:
Dim SNAME As String
Dim NTURN As Integer
If NTURN = 0 Then
If SNAME = "vbeden" Then
Do While NTURN < 4
NTURN = NTURN + 1
Loop
End If
End If
Easy to read code:
Dim sName As String
Dim nTurn As Integer
If nTurn = 0 Then
If sName = "vbeden" Then
Do While nTurn < 4
nTurn = nTurn + 1
Loop
End If
End If
[return to index]
3. Please develop the following good habits of "object naming convention"
Recommended control prefixes
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 box cbo cboEnglish
Command button cmd cmdExit
Common dialog dlg dlgFileOpen
Communications com comFax
Control (used in procedures when the specific type is unknown) ctr ctrCurrent
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
GraphgragraRevenue
Grid grd grdPrices
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 button lwcmd lwcmdRemove
Lightweight frame lwfra lwfraSaveOptions
Lightweight horizontal scroll bar lwhsb lwhsbVolume
Lightweight list box lwlst lwlstCostCenters
Lightweight option button lwopt lwoptIncomeLevel
Lightweight text box lwtxt lwoptStreet
Lightweight vertical scroll bar lwvsb lwvsbYear
Line lin linVertical
List box lst lstPolicyCodes
ListView lvw lvwHeadings
MAPI message mpm mpmSentMessage
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
Timer tmr tmrAlarm
Toolbar tlb tlbActions
TreeView tre treOrganization
UpDown upd updDirection
Vertical scroll bar vsb vsbRate
-------------------------------------------------- ----------------------------------
Recommended prefixes for Data Access Objects (DAO)
Use the following prefixes to indicate data access objects
Database object prefix example
Container conconReports
Database db dbAccounts
DBEngine dbe dbeJet
Document doc docSalesReport
Field fld fldAddress
Group grp grpFinance
Index ix idxAge
Parameter prm prmJobCode
QueryDef qry qrySalesByRegion
Recordset rec recForecast
Relation rel relEmployeeDept
TableDef tbd tbdCustomers
User usr usrNew
Workspace wsp wspMine
-------------------------------------------------- ----------------------------------
Applications frequently use many menu controls, and it is useful to have a unique set of naming conventions for these controls. In addition to the initial "mnu" tag, the menu control's prefix should be expanded: an additional prefix is added for each level of nesting, placing the final menu title at the end of the name string. The table below lists some examples.
Recommended menu prefixes
Menu title sequence menu handler name
File Open mnuFileOpen
File Send Email mnuFileSendEmail
File Send Fax mnuFileSendFax
Format Character mnuFormatCharacter
Help Contents mnuHelpContents
When you use this naming convention, all members of a specific menu group are listed one after another in the Visual Basic Properties window. Furthermore, menu control names clearly indicate the menu items to which they belong.
Choose a prefix for other controls
Controls not listed above should be standardized with a unique two- or three-character prefix for consistency. Use prefixes longer than three characters only when clarification is required.
Constant and variable naming conventions
In addition to objects, constants and variables also require well-formed naming conventions. This section lists the recommended conventions for constants and variables that Visual Basic supports. and discusses issues of identifying data types and ranges.
Variables should always be defined in the smallest possible scope. Global (Public) variables can lead to extremely complex state structures and make an application's logic very difficult to understand. Global variables also make code reuse and maintenance more difficult.
Variables in Visual Basic can have the following scopes
scope declaration position visible position
'Private' in a procedure-level procedure, sub-procedure or function procedure in the procedure in which it is declared
'Private' in the declaration section of a module-level form or code module (.frm, .bas) Every procedure in a form or code module
'Public' in the declarations section of the global code module (.bas) everywhere in the application
In a Visual Basic application, use global variables only when there is no other convenient way to share data between forms. When global variables must be used, declare them in a single module and group them by function. Give this module a meaningful name to indicate its role, such as Public.bas.
A good coding practice is to write code that is as modular as possible. For example, if your application displays a dialog box, put all the controls and code needed to complete the dialog box in a single form. This helps organize the application's code into useful components and reduces its runtime overhead.
With the exception of global variables (which should not be passed around), procedures and functions should only operate on the objects passed to them. Global variables used within a procedure should be identified in the declaration section at the beginning of the procedure. In addition, ByVal should be used to pass parameters to Sub procedures and function procedures, unless there is an obvious need to change the passed parameter value.
As the size of the project grows, the work of scoping variables increases rapidly. Placing a single-letter range prefix in front of the type prefix marks this growth, but the length of the variable name does not increase by much.
variable scope prefix
Range prefix example
global gstrUserName
Module level mmblnCalcInProgress
Local to process without dblVelocity
If a variable is declared as Public in a standard module or a form module, then the variable has global scope. If a variable is declared Private in a standard module or a form module respectively, then the variable has module-level scope.
Note: Consistency is key to using this technique effectively; the syntax checker in Visual Basic will not catch module-level variables that begin with "p."
constant
The body of a constant name is mixed case, with the first letter of each word capitalized. Although standard Visual Basic constants do not contain data type and range information, prefixes such as i, s, g, and m are useful for understanding the value and range of a constant. For constant names, the same rules should be followed as for variables. For example:
mintUserListMax 'Maximum limit on user list
'(integer value, local to module)
gstrNewLine 'New line character
'(String, used globally by the application)
variable
Declaring all variables will save programming time because there will be fewer errors caused by typing operations (for example, is it aUserNameTmp, sUserNameTmp, or sUserNameTemp). In the Editor tab of the Options dialog box, check the Require variable declaration option. The Option Explicit statement requires that all variables be declared in the Visual Basic program.
Variables should be prefixed to indicate their data type. And the prefix can be expanded to indicate variable scope, especially for large programs.
Use the following prefixes to indicate the data type of a variable.
Variable data type
Data type prefix example
String (String type) str strFName
Integer (short integer type) int intQuantity
Long (long integer type) lng lngDistance
Single (single precision floating point number type) sng sngAverage
Double (double precision floating point type) dbl dblTolerance
Boolean (Boolean type) bln blnFound
Byte (byte type) byt bytRasterData
Date (date type) dte dteNow
Currency (currency calculation and fixed-point calculation type) cur curRevenue
Object (object type) obj objCurrent
Variant vnt vntCheckSum
Describe variable and procedure names
The body of a variable or procedure name should be in mixed case and should be long enough to describe its purpose. Also, the function name should start with a verb, such as InitNameArray or CloseDialog.
For frequently used or long terms, it is recommended to use standard abbreviations to rationalize the length of the name. Generally speaking, variable names longer than 32 characters are difficult to read on a VGA monitor.
When using abbreviations, make sure they are consistent throughout the application. In a project, if you use Cnt for a while and Count for a while, it will lead to unnecessary confusion.
user-defined type
In a large project with many user-defined types, it is often necessary to give each type its own three-character prefix. If these prefixes start with "u", it is easy to quickly identify these types when working with a user-defined type. For example, ucli can be used as a prefix for a user-defined client type variable.
[return to index]
4. In the case of simple selection conditions, use the IIf() function
Rosso's code:
If nNum = 0 Then
sName = "sancy"
Else
sName = "Xu"
End If
Simple code:
sName=IIf(nNum=0,"sancy","Xu")
5. Try to use Debug.Print for debugging
In many beginners' debugging, MsgBox is used to track variable values. In fact, Debug.Print can not only achieve the same effect, but will also be ignored during the final compilation of the program. MsgBox must be manually commented or deleted.
generally:
MsgBox nName
should:
Debug.Print nName
6. When repeatedly modifying the properties of an object, try to use With....End With
generally:
Form1.Height = 5000
Form1.Width = 6000
Form1.Caption = "This is MyLabel"
should:
With Form1
.Height = 5000
.Width = 6000
.Caption = "This is MyLabel"
End With
Program execution efficiency of this structure is relatively high, especially in loop statements.
7. Try to use message icons in MsgBox so that the program is more standardized.
Generally speaking
vbInformation is a message used to prompt confirmation or successful operation
vbExclamation is used to prompt warning messages
vbCritical messages used to prompt crisis situations
vbQuestion is a message used to prompt questions
[return to index]
8. Use enumerations where possible
The format of the enumeration is
[Public | Private] Enum name
membername [= constantexpression]
membername [= constantexpression]
....
End Enum
The Enum statement contains the following parts:
partial description
Public Optional. Indicates that the Enum type is visible throughout the project. The default for Enum types is Public.
Private Optional. Indicates that the Enum type is only visible in the declared module.
name required. The name of this Enum type. name must be a legal Visual Basic identifier that is used to specify the type when defining a variable or parameter of this Enum type.
membername required. A legal Visual Basic identifier that specifies the name of the constituent elements of this Enum type.
constantexpression optional. The value of the element (of type Long). Can be other Enum types. If constantexpression is not specified, the assigned value is either 0 (if the element is the first membername), or one greater than the value of its immediate predecessor.
illustrate
The so-called enumeration variables refer to variables defined with the Enum type. Both variables and parameters can be defined as Enum type. Elements of the Enum type are initialized to the constant value specified in the Enum statement. The assigned value can include positive and negative numbers and cannot be changed at runtime. For example:
Enum SecurityLevel IllegalEntry = -1 SecurityLevel1 = 0 SecurityLevel2 = 1 End Enum
Enum statements can only appear at the module level. After defining the Enum type, you can use it to define variables, parameters, or procedures that return that type. Enum types cannot be qualified with module names. Public Enum types in a class module are not members of the class; they are simply written to the type library. Enum types defined in standard modules are not written to the type library. Public Enum types with the same name cannot be defined in both a standard module and a class module because they share the same namespace. If there are two Enum types in different type libraries with the same name but different members, the reference to a variable of this type will depend on which type library has a higher reference priority.
You cannot use the Enum type as a target in a With block.
Enum statement example
The following example demonstrates using the Enum statement to define a collection of named constants. In this case there are some selectable color constants used to design the data entry form for the database.
Public Enum InterfaceColors
icMistyRose = &HE1E4FF&
icSlateGray = &H908070&
icDodgerBlue = &HFF901E&
icDeepSkyBlue = &HFFFF00&
icSpringGreen = &H7FFF00&
icForestGreen = &H228B22&
icGoldenrod = &H20A5DA&
icFirebrick = &H2222B2&
End Enum
The advantage is that it speeds up programming