Eight good habits of VB programming
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....EndWith
7. Try to use message icons in MsgBox so that the program is more standardized.
8. Use enumerations where 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:
DimsMessageAsString
sMessage="1"+"2"
correct:
DimsMessageAsString
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:
DimSNAMEAsString
DimNTURNAsInteger
IfNTURN=0Then
IfSNAME="vbeden"Then
DoWhileNTURN<4
NTURN=NTURN+1
Loop
EndIf
EndIf
Easy to read code:
DimsNameAsString
DimnTurnAsInteger
IfnTurn=0Then
IfsName="vbeden"Then
DoWhileTurn<4
nTurn=nTurn+1
Loop
EndIf
EndIf
[return to index]
3. Please develop the following good habits of "object naming convention"
Recommended control prefixes
Control type prefix example
3DPanelpnlpnlGroup
ADODataadoadoBiblio
AnimatedbuttonanianiMailBox
CheckboxchkchkReadOnly
Combobox,drop-downlistboxcbocboEnglish
CommandbuttoncmdcmdExit
CommondialogdlgdlgFileOpen
CommunicationscomcomFax
Control (used in procedures when the specific type is unknown) ctrctrCurrent
DatadatdatBiblio
Data-boundcomboboxdbcbodbcboLanguage
Data-boundgriddbgrddbgrdQueryResult
Data-boundlistboxdblstdblstJobType
DatacombodbcdbcAuthor
DatagriddgddgdTitles
DatalistdbldblPublisher
DatarepeaterdrpdrpLocation
DatepickerdtpdtpPublished
DirectorylistboxdirdirSource
DrivelistboxdrvdrvTarget
FilelistboxfilfilSource
FlatscrollbarfsbfsbMove
FormfrmfrmEntry
FramefrafraLanguage
GaugegaugauStatus
GraphgragraRevenue
GridgrdgrdPrices
HierarchicalflexgridflexflexOrders
HorizontalscrollbarhsbhsbVolume
ImageimgimgIcon
ImagecomboimgcboimgcboProduct
ImageListilsilsAllIcons
LabellbllblHelpMessage
LightweightcheckboxlwchklwchkArchive
LightweightcomboboxlwcbolwcboGerman
LightweightcommandbuttonlwcmdlwcmdRemove
LightweightframelwfralwfraSaveOptions
LightweighthorizontalscrollbarlwhsblwhsbVolume
LightweightlistboxlwlstlwlstCostCenters
LightweightoptionbuttonlwoptlwoptIncomeLevel
LightweighttextboxlwtxtlwoptStreet
LightweightverticalscrollbarlwvsblwvsbYear
LinelinlinVertical
ListboxlstlstPolicyCodes
ListViewlvwlvwHeadings
MAPImessagempmmpmSentMessage
MAPIsessionmpsmpsSession
MCImcimciVideo
MenumnumnuFileOpen
MonthviewmvwmvwPeriod
MSChartchchSalesbyRegion
MSFlexgridmsgmsgClients
MSTabmstmstFirst
OLEcontaineroleoleWorksheet
OptionbuttonoptoptGender
PictureboxpicpicVGA
PictureclipclpclpToolbar
ProgressBarprgprgLoadFile
RemoteDatardrdTitles
RichTextBoxrtfrtfReport
ShapeshpshpCircle
SlidersldsldScale
SpinspnspnPages
StatusBarstastaDateTime
SysInfosyssysMonitor
TabStriptabtabOptions
TextboxtxttxtLastName
TimertmrtmrAlarm
ToolbartlbtlbActions
TreeViewtretreOrganization
UpDownupdupdDirection
VerticalscrollbarvsbvsbRate
-------------------------------------------------- ----------------------------------
Recommended prefixes for Data Access Objects (DAO)
Use the following prefixes to indicate data access objects
Database object prefix example
ContainerconconReports
DatabasedbdbAccounts
DBEnginedbedbeJet
DocumentdocdocSalesReport
FieldfldfldAddress
GroupgrpgrpFinance
IndexixidxAge
ParameterprmprmJobCode
QueryDefqryqrySalesByRegion
RecordsetrecrecForecast
RelationrelrelEmployeeDept
TableDeftbdtbdCustomers
UserusrusrNew
WorkspacewspwspMine
-------------------------------------------------- ----------------------------------
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
FileOpenmnuFileOpen
FileSendEmailmnuFileSendEmail
FileSendFaxmnuFileSendFax
FormatCharacternuFormatCharacter
HelpContentsmnuHelpContents
When this naming convention is used, 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 supported by Visual Basic. 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' form in the declaration section of a module-level form or code module (.frm, .bas) or every procedure in a code module
Everywhere in the 'Public' application in the declarations section of the global code module (.bas)
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.
1 2Read the full text on the next page