VB programming 8 tips

xiaoxiao2021-03-06  86

1

, "&" Replace " " In many people's programming languages, use " " to connect the string, which is easy to cause ambiguity. Good habits are "&" to connect the string.

Incorrect:

Dim SMESSAGE AS STRING

SMESSAGE = "1" "2"

correct:

Dim SMESSAGE AS STRING

SMESSAGE = "1" & "2"

Note: "&" has a space

2, variable name sensation,

Statement is wrong with rank, source code maintenance

Here's you compare the following two codes:

Read the code that is difficult to know:

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 the 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 develop the following "object naming conventions" good habits

Recommended control prefix

Control type prefix example

3D PANEL PNL PNLGroup

ADO Data Ado Adobe Iblio

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 (when a specific type is unknown, in the process) 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 DGDTISLES

Data List DBL DBLPUBLISHER

Data Repeater Drp Drplocation

Date Picker DTP DTPPBLISHED

Directory List Box Dir Dirsource

Drive List box drv drvtarget

File List Box FilSource

Flat Scroll Bar FSB FSBMOVE

Form FRM FRMENTRY

Frame fraranguage

Gauge Gau Gaustatus

Graph gra grandevenue

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 Data Access Object (DAO) prefix

Use the following prefix to indicate data access objects

Database object prefix example

Container ConReports

Database DB DBACCOUNTS

DBENGINE DBE DBEJET

Document Doc DocsalesReport

FIELD FLD FLDDRESS

GROUP GRP GRPFINANCE

Index IX IDXAGE

Parameter prmjobcode

QueryDef Qry QrysalesbyRegion

Recordset Rec Recforcast

RELATION REL RELEMPLOYEDEPT

Tabledef TBD TBDCUSTOMERS

User usr usrnew

Workspace WSP Wspmine

-------------------------------------------------- ------------------------------ Application frequently uses many menu controls, which has a set of unique naming conventions for these controls. . In addition to the top "MNU" tag, the prefix of the menu control should be extended: add an additional prefix for each stage, put the header of the final menu in the last menu. The following table lists some examples.

Recommended menu prefix

Menu Title Sequence Menu Processor Name

File Open Mnufileopen

File Send Email Mnufilesendemail

File Send Fax Mnufilesendfax

Format Character MnuFormatcharacter

Help Contents MNUHELPCONTENTS

When using this naming convention, all members of a specific menu group take one of the listings in the "Properties" window of Visual Basic. Moreover, the name of the menu control clearly shows the menu items they belong.

Select prefix for other controls

For controls listed above, you should use the unique prefix consisting of two or three characters to standardize to keep consistency. More than three characters are used only when it is necessary to clarify.

Constants and variable naming conventions

In addition to objects, constants and variables also require a good format naming convention. This section lists the recommendations of constants and variables supported by Visual Basic. And discuss issues that identify data types and ranges.

Variables should always be defined within a small range as possible. The global (public) variable can lead to extremely complex state agencies, and make the logic of an application very difficult to understand. Global variables also make the reuse and maintenance of the code more difficult.

Variables in Visual Basic can have the following range

Scope declaration location visible location

Process grade process, sub-process or function of 'private' during declaring it

Module-Level Forms or Code Module (.frm, .bas) declaration section of the 'private' form or code module

Each of the 'Public' application in the declaration section of the global code module (.bas)

In Visual Basic's applications, global variables are only used when there is no other convenient way to share data between the form. When you have to use global variables, they declare them in a single module and packet according to the function. Take a meaningful name to this module to indicate its role, such as public.bas.

Good coding habits are to write modular code as much as possible. For example, if the application displays a dialog, all controls and code you want to complete this dialog task are placed in a single form. This helps to use the application's code organization in useful components and reduce the overhead of its runtime.

In addition to global variables (should be not delivered), processes and functions should only be operated only for objects passed to them. The global variable used in the process should be identified in the declaration section of the process start. In addition, you should deliver parameters to the SUB process and the Function process, unless it is clear that the passed parameter value is changed.

With the growth of project size, the work of dividing variable ranges is also increased. The single-alphabet prefix is ​​launched in front of the type prefix indicates this growth, but the length of the variable name does not increase.

Variable range prefix

Range prefix example

GGSTRUSERNAME

Modular grade M MblncalcinProgress

Local until there is no dblvelocity

If a variable is declared in the standard module or form module as public, then the variable has a global range. If a variable is declared as private in a standard module or form module, then the variable has a modular level.

Note: Consistency is a key to use this technology. The syntax inspector in Visual Basic does not capture module-level variables starting with "p.". constant

The main body of constant quantities is mixed, and the first letter of each word is capitalized. Although standard Visual Basic constants do not contain data types and range information, prefixes such as I, S, G, and M are still very useful for understanding the value and range of a constant. For constant names, the same rules as variables should be followed. E.g:

MINTUSERLISTMAX 'Maximum limit on the user list

'(Integer value, local to module)

GSTRNEWLINE 'new line characters

'(String, global use of applications)

variable

Declarening all variables will save programming time, because the error caused by typing operations is reduced (for example, is AUSERNAMETMP, or SUSERNAMETMP, or SUSERNAMETEMP). In the Editor tab of the Options dialog, check the "Requirements Variable Declaration" option. Option EXPLICIT statement requires that all variables are declared in the Visual Basic program.

It should be given to the variable to indicate their data type. Moreover, the prefix can be expanded to indicate the range of variables, 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 Negative Type) Int IntQuantity

Long (Long Integer Type) LNG LNGDISTANCE

SINGLE (single-precision floating point number) SNG SNGAVERAGE

Double (double precision floating point type) DBL DBLTOLERANCE

Boolean (Boolean) 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 (variant type) VNT VNTCHECKSUM

Describe variables and process names

The subjects of the variable or process name should be in size and should be sufficiently long enough to describe its role. Moreover, the function name should be in one verb, such as initNameArray or Closedialog.

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

When using a thumbnail, make sure they are consistency throughout the application. In one project, if you use CNT for a while, you will use count, which will result in unnecessary confusion.

User-defined type

In a big project with many user-defined types, it is often necessary to give each type of one of its own three characters prefixed. If these prefix starts with "U", quickly identify these types when using a user-defined type. For example, UCLI can be used as a prefix for a user-defined customer type variable.

4 Use the IIF () function in a simple selection condition

Rosso 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 the commissioning of many beginners, use MSGBOX

Track the variable value. In fact, debug.print can not only reach the same effect, but also in the final compilation process of the program. The MSGBOX must be manually annotated or deleted.

usually:

Msgbox nname

should:

Debug.print nname

6,

Try to use with .... end with when you repeat the properties of a certain object

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 high efficiency, especially in the cycle statement.

7.

Msgbox Try to use the message icon as much as possible, this program is more specified

Generally

Vbinformation is used to prompt the message to confirm or successfully operate

Vbexclamation is used to prompt the message

Vbcritical is used to prompt the crisis

Vbquestion is used to prompt the message

8,

Use enumeration in may be

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 is optional. Indicates that the Enum type is visible throughout the project. The default situation of the Enum type is public.

Private is optional. Indicates that the Enum type is only visible only in the declared module.

Name must be. The name of the enum type. Name must be a legitimate Visual Basic identifier that specifies the type with this name when defining a variable or parameter of the enum type.

MEMBERNAME is required. A legitimate Visual Basic identifier for specifying the constituent element name of the enum type.

Constantexpression is optional. The value of the element (for long type). Can be an other ENUM type. If there is no ConstantExpression, the value is given or 0 (if the element is the first memory), or the value is larger than its direct forward.

Description

The so-called enumeration variable refers to the variable defined with the enum type. Variables and parameters can be defined as an ENUM type. Elements in the ENUM type are initialized to the constant value specified in the ENUM statement. The value given can include positive and negative numbers, and cannot be changed at runtime. E.g:

Enum security = -1 securityLevel1 = 0 securityLevel2 = 1 END ENUM

The Enum statement can only appear in the module level. Once you define the ENUM type, you can use it to define variables, parameters, or return to this type. You cannot use the module name to limit the enum type. The PUBLIC ENUM type in the class module is not a member of the class; but they are also written to the type library. The ENUM type defined in the standard module is not written in the type library. Public enorm types with the same name cannot be defined in a standard module, and are defined in class modules because they share the same namespace. If there are two eNUM types in different types of libraries, the membership of this type of variable will depend on which type library has a higher reference priority. Enum types cannot be used as the target in the With block.

ENUM statement example

The following example demonstrates a collection of naming constants with an ENUM statement. In this example, some of the color constants that can be selected for designing the data input form of the database.

Public Enum InterfaceColors

ICMistyRose = & HE1E4FF & HE1E4FF & HE1E4FF & HE1E4FF & HE1E4FF & HE1E4FF &

Icslategray = & h908070 & h908070

IcdodgerBlue = & HFF901E & HFF901E &

IcdeepskyBlue = & HFFBF00 &

Icspringgreen = & h7fff00 &

IcForeStgreen = & H228B22 & H228B22 &

Icgoldenrod = & H20A5DA & H20A5DA &

ICFIREBRICK = & H2222B2 & H2222B2 & H2222B2 & H2222B2 & H2222B2 & H2222B2 & H2222B2 &

END ENUM

The advantage is to speed up the programming speed

9 When writing code, you can write a variable using Chinese, and then use English. When you write the code, your thinking is relatively clear, and it is convenient to debug, hehe.

转载请注明原文地址:https://www.9cbs.com/read-94727.html

New Post(0)