8 Tips for VB programming

Source: Internet
Author: User
Tags constant integer mixed naming convention ole range ranges require
Programming | Tips 1, "&" Replace "+"
In many people's programming languages, "+" is used to connect strings, which can lead to ambiguity. A good habit is to use "&" to connect strings.

Not correct:
Dim Smessage as String
smessage = "1" + "2"

That's right:
Dim Smessage as String
smessage = "1" & "2"

Note: There is a space at the back of "&"

2, variable naming case, the statement scattered with rank, source code maintenance aspects

Below you compare the following two paragraph code:

Read and understand the most 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

3 Please form the following "object naming convention" good Habits

The recommended control prefix

Example of a control type prefix
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 the procedure when a particular 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
Graph GRA Grarevenue
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

--------------------------------------------------------------------------------
Prefix of the recommended data Access object (DAO)
Use the following prefix to indicate the data Access object
Database Object Prefix Example
Container Con conreports
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 use many menu controls frequently, and it is practical to have a unique set of naming conventions for these controls. In addition to the first "MNU" tag, the prefix of the menu control should be extended: Adds an additional prefix to each level of nesting, placing the final menu title at the end of the name string. The following table lists some examples.

Recommended Menu Prefixes
Menu title sequence Menu Processor 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 particular menu group are listed one after another in the Properties window of Visual Basic. Also, the name of the menu control clearly indicates the menu item to which they belong.

Select a prefix for other controls

For controls that are not listed above, you should standardize them with a unique two-or three-character prefix to maintain consistency. Prefix with more than three characters is used only if clarification is required.

Constants and variable naming conventions
In addition to objects, constants and variables require a well-formed naming convention. This section lists the recommended conventions for constants and variables that are supported by Visual Basic. and discusses issues that identify data types and scopes.

Variables should always be defined in as small a range as possible. Global (public) variables can cause extremely complex state mechanisms and make the logic of an application very difficult to understand. Global variables also make code more difficult to reuse and maintain.

Variables in Visual Basic can have the following ranges

Scope Declaration Location Visible Location
Process-level procedure, the ' Private ' in the process of a subroutine or function, in the process of declaring it
Each procedure in the ' Private ' form or code module in the Declarations section of a module-level form or code module (. frm,. bas)
Every place in the ' public ' application in the Declarations section of the Global Code module (. bas)

In Visual Basic applications, global variables are used only when there is no other convenient way to share data between forms. When global variables must be used, they are declared in a single module and grouped by function. Give the module a meaningful name to indicate its role, such as Public.bas.

A good coding habit is to write modular code as much as possible. For example, if your application displays a dialog box, put all the controls and code you need to complete this dialog task in a single form. This helps to organize your application's code into useful components and to reduce the overhead of running it.

In addition to global variables (which should not be passed), procedures and functions should operate only on objects passed to them. The global variables used in the procedure should be identified in the Declarations section at the beginning of the procedure. In addition, you should use ByVal to pass parameters to Sub procedures and function procedures, unless you obviously need to change the passed parameter values.

With the increase of project size, the work of dividing the range of variables is also increasing rapidly. Placing a single letter-range prefix on the prefix of the type indicates this growth, but the length of the variable name does not increase much.

Variable range prefix

Scope Prefix Example
Global g gstrUserName
Module-level M mblncalcinprogress
Local to procedure without dblvelocity

If a variable is declared public in a standard module or form module, the variable has a global scope. If a variable is declared Private in a standard module or form module, then the variable has a module-level scope.

Note: Consistency is the key to effective use of this technology; The grammar checker in Visual Basic does not capture 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 values and ranges of a constant. For constant names, follow the same rules as the variables. For example:

Mintuserlistmax ' Maximum limit on the list of users
' (integer value, local to module)
Gstrnewline ' New line character
' (String, application global use)

Variable
Declaring all the variables will save programming time, because the error caused by typing is reduced (for example, whether it's 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 a Visual Basic program.

Variables should be prefixed to indicate their data type. And the prefix can be extended to indicate the scope of the variable, especially for large programs.

Use the following prefix 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 (length integer type) LNG lngdistance
Single (single-precision floating-point number type) SNG sngaverage
Double (double-precision floating-point number 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 (objects type) obj objcurrent
Variant (variant type) vnt Vntchecksum

Describe variables and procedure names

The body of a variable or procedure name should be in mixed case and should be long enough to describe its effect. Also, the function name should begin with a verb, such as initnamearray or Closedialog.

For frequently used or long items, it is recommended to use standard abbreviations to rationalize the length of the name. In general, a variable name of more than 32 characters is difficult to read on a VGA display.

When using abbreviations, make sure they are consistent throughout the application. In one project, if you use Cnt for a while, using Count for a while will result in unnecessary confusion.

User-defined Types
In a large project with many user-defined types, it is often necessary to give each type a prefix of its own three characters. If these prefixes start with "U", it is easy to identify these types quickly when working with a user-defined type. For example, UCLI can be used as a prefix for a user-defined customer type variable.

4 using the IIF () function in the case of simple selection conditions

Russell'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, using Debug.Print can not only achieve the same effect, but also in the process of final compilation, will be ignored. And MsgBox must be manually annotated or deleted.

Usually:
MsgBox Nname

Should:
Debug.Print Nname

6. When modifying the properties of an object, try to use with .... End With

Usually:
Form1.height = 5000
Form1.width = 6000
Form1.caption = "This is MyLabel"

Should:
With Form1
. Height = 5000
. Width = 6000
. Caption = "This is MyLabel"
End With
This structural program performs more efficiently, especially in circular statements.

7, MsgBox Use the message icon as far as possible, so the program is more standardized

Generally speaking

vbinformation message used to prompt for confirmation or successful operation

Vbexclamation a message to prompt for a warning

Vbcritical used to hint at a crisis situation.

Vbquestion message to Prompt for inquiries

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 sections:

Partial description
Public optional. Indicates that the Enum type is visible throughout the project. The default case for the Enum type is public.
Private Optional. Indicates that the Enum type is visible only in the declared module.
Name is required. The name of the Enum type. Name must be a legitimate Visual Basic identifier that specifies the type when you define a variable or parameter of that type of Enum.
MemberName is required. The legitimate Visual Basic identifier that specifies the name of the constituent element for this Enum type.
ConstantExpression is optional. The value of the element (a Long type). Can be another Enum type. If ConstantExpression is not specified, the value assigned is either 0 (if the element is the first membername), or 1 greater than the value of its immediate predecessor.

Description
An enumeration variable is a variable that is defined with an enum type. Both variables and parameters can be defined as Enum types. Elements in the enum type are initialized to the constant value specified in the enum statement. The value assigned can include positive and negative numbers, and cannot be changed at run time. For example:

Enum SecurityLevel illegalentry =-1 SecurityLevel1 = 0 SecurityLevel2 = 1 End enum

The Enum statement can only appear at the module level. After you define an Enum type, you can use it to define a variable, a parameter, or a procedure that returns that type. You cannot qualify an Enum type with a module name. The public Enum type in the class module is not a member of the class, except that they are also written to the type library. The type of Enum defined in the standard module is not written to the type library. Public Enum types with the same name cannot be defined both in standard modules and in class modules because they share the same namespaces. If there are two Enum types in different type libraries with the same names, but different members, references to variables 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.

Example of an Enum statement
The following example shows a collection that defines a named constant with an Enum statement. In this case, some of the color constants you can select are used to design the data entry form for the database.

Public Enum Interfacecolors
Icmistyrose = &HE1E4FF&
Icslategray = &H908070&
Icdodgerblue = &HFF901E&
Icdeepskyblue = &HFFBF00&
Icspringgreen = &H7FFF00&
Icforestgreen = &H228B22&
Icgoldenrod = &H20A5DA&
Icfirebrick = &H2222B2&
End Enum

The advantage is to speed up the programming speed
9 Write the code, you can write variables in Chinese, finished after the replacement in English. This writing code when the idea is more clear, and easy to debug, hehe.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.