Visual BASIC Programming specification

Source: Internet
Author: User
Tags empty error handling execution expression goto naming convention ole variables
Visual| Programming | specification

Visual BASIC Programming specification

1. Visual Basic IDE (Integrated development Environment) settings

You must turn on the Require variable declaration for setting options, align controls to grid, auto indent switch. The tab width is 4 spaces and the grid units are set to: Width 60.

2. Naming convention

(Note: You cannot use Chinese and full-width characters at any time, only English letters, underscores, and numbers are allowed)

2.1 Designation of the project

ActiveX controls and DLL engineering named format (... Lib), EXE project directly named, if it is a generic component project, directly named, if it is a project or product engineering, use the project or product abbreviation as a prefix.        such as: Xwy....lib. Project naming does not have to be abbreviated, in order to express meaning and use, can be as long as possible, and the name format used (noun), (adjective + noun) or (noun + verb noun form). such as: Stockoperationlib or Stocklib.

2.2 Name of the variable

The variables in the program follow the Hungarian notation, which is "prefix + variable meaning", and the meaning of the variable is one or more English words, and the first letter of each word is capitalized. The variable prefix is three lowercase letters indicating its type, and the prefix you need to add follows Microsoft's recommendation in MSDN. The list is as follows: For general counter variable definitions, it should be as simple as possible, such as: Dim i as integerfor i = 0 to 100Next I range identification:

global variable plus prefix: ' g_ ' for example: g_strfdbm

Module-level variable prefix: ' m_ ' for example: m_strfdbm

Process-level variables are not prefixed global variables and module-level variables should use full names as much as possible, and abbreviations are not recommended, such as: gentitymanager common variable types and control type prefixes are shown in the following table: Variable type prefix list

Data type

Prefix

Example

Boolean

bln

Blnloggedin

Currency

Cur

Cursalary

Control

Ctl

Ctllastcontrol

Double

Dbl

Dblmiles

ErrObject

Err

Errlasterror

Single

Sng

Sngyears

Handle

Hwd

Hwdpicture

Long

Lng

Lngonhand

Object

Obj

Objusertable

Integer

Int

IntAge

String

Str

StrName

user-defined type

Udt

Udtemployee

Variant (including dates)

Vnt

Vntdatehired

Array

Arr

Arremployees database object Prefix sample db

Dbs

Dbsaccounts Recordset

Rec

Recforecast command

Cmd

Cmdquery Connection

Con

Consql

2.3 Naming of controls

Control naming all uses the control type abbreviation + the control uses the naming method, the abbreviation rule and the variable name, the following is the commonly used control's type abbreviation, should strictly observe. If a new control (including an upgraded version) is used, a request must be made to the company, and after the review is passed, the type name abbreviation is coordinated and used again. control type prefix list

Control

Prefix

Example

ADO Data

Ado

Adobiblio

Animated button

Ani

Animailbox

Checkbox

Chk

Chkprint

Combo Box

Cbo

Cbotitle

Command button

Cmd

Cmdcancel

Communications

Com

Comfax

Data

Dat

Datbiblio

Data-bound combo Box

Dbcbo

Dbcbolanguage

Data-bound Grid

Dbgrd

Dbgrdqueryresult

Common Dialog Control

Dlg

Dlgcommon

Control

Ctr

Ctrcurrent

Directory list Box

Dir

Dirsource

Drive list Box

Drv

Drvtarget

DTPicker Dropdatecontrol

Dt

Enumeditbox

Enm

File list Box

Fil

Filsource

Frame

Fra

Fralanguage

Form

frm

Frmmain

Vfgrid

Grd

Graph

Gra

Group push button

Gpb

Gpbchannel

Hierarchical FlexGrid

Flex

Flexorders

Horizontal scroll bar

Hsb

Hsbvolume

Image

Img

Imgicon

Image ImageList

Img

Label

LbL

Lblhelpmessage

Line

Lin

Linvertical

List Box

Lst

Lstresultcodes

Listview

Lv

Mci

Mci

Mcivideo

MDI child Form

Mdi

Mdicontact

Menu Control

Mnu

Mnufileopen

Numeditbox

Nm

OLE container

Ole

Olephoto

Option button

Opt

Optspanish

Panel

PnL

Pnlsettings

Picture box

Pic

Picdiskspace

Picture clip

Clp

Clptoolbar

ProgressBar

Prg

Prgloadfile

The

Rpt

Scroll Bar

Sbr

Shape

shp

Shpcircle

Slider

Sld

Sldscale

Spin

Spn

StatusBar

St

ToolBar

Tb

Text Box

Txt

Txtaddress

Timer

Tmr

Tmralarm

Treeview

Tv

Tvflbm

Vertical scroll bar

Vsb

Vsbrate

2.4 Nomenclature of functions and procedures

The functions here include sub and function, and the following two procedures are collectively called functions. The function represents an action, so its structure should be verb + noun, verb must be lowercase, followed by the first letter of the name, such as: Getmaterialcodeupdategridreadorder function name as far as possible not to use abbreviations, and its name should make people at a glance,       To know the function of this function from the name, do not use meaningless function names, such as: Getcode,update,readdata.       When the function name is not sufficient to express its function, use the function header plus a comment that gives the caller sufficient understanding. Parameter naming: The principle of parameter naming is all lowercase, if the argument includes two or more words, the first word letter lowercase, other words first letter uppercase, such as Showcol, Isupdate.

2.5 The name of the constant

The name of a constant should all be capitalized, using ' _ ' as the separator between words, the word as much as possible using a full name, such as: Public Const msg_empty_row as String = "There are empty rows!" "Explanation: (1) abbreviations should be used for some common words, such as MSG (2) using public to declare constants (3) The declaration of a constant must be of type, as the String above

2.6 Naming of properties

The name of the attribute takes the principle of first letter capitalization, such as ItemCount Item

2.7 Naming of classes, forms, and modules

Class is named: CLS prefix + functional noun, and the first letter of the word is capitalized. For example: Clssystemconfig form naming: Use the frm prefix + functional noun, and capitalize the first letter of the word.        such as: Frmlist. Module Name: MoD prefix + functional noun, and capitalize the first letter of the word. such as Modlist. The above three kinds of names must remain unique within a project.

2.8 Naming of custom controls

Name of the custom control: noun + Ctrl as: Editgridctrl

3. Writing format conventions

3.1 Definition

The defined code block should be put together, do not define the variable in the middle, the definition of the variable should be on top of the line, not indented.

As follows: Dim I as Integerdim J as Integerdim em as Entitymanager object should be defined as the name of the library to which it belongs, preventing future name collisions, such as referencing two lib, each containing A stock class, if you do not use as .... lib.stock definition, you cannot compile the pass, in order to prevent future expansion and modification of the introduction of a new library to bring naming conflicts, it is recommended to define class objects all with library identity, such as: Dim em as OBJECTP Ersistencelib.entitymanager

3.2 Blank Lines

A blank line is the interval between code blocks and blocks, and a blank line must be added between functions (about two rows). Within the function, the variable declaration block and the implementation block (the implementation block refers to the other code except the variable declaration) to use a blank line to interval (a row), implement the interior of the block, through a blank line to identify a functional segment, such as: Private Sub Check (order as Nysalebacklib.order)

' Reduce inventory Dim Objstockitem as Nystocklib.stockitemdim Objstock as Nystocklib.stockdim i as Integer Set objstock = createst Ock () for i = 0 to order.itemcount-1 Set objstockitem = Order.item (i)

' Reduce inventory call Objstock.reduceitem (Objstockitem, True) Next i Set objstock = no end Sub

(Note: Do not use too many blank lines, empty lines too much affect code reading!) )

3.3 Indent

Indentation must be strictly enforced, variable declaration block is not indented, the implementation block must ensure that all indents (that is, the implementation block is not possible to align). The code for each unit is indented to a tab, and the unrelated code leaves a blank interval.

Note: Goto label does not indent for basic control structure, must have indentation, such as: If, do, with, for, OPEN, select block, indented example: Private Function getmax (Byref lngarray () as Long) As Long dim Lngmax As Long Dim lngcount As Long getmax=0 for Lngcount =0 to Ubound (Lngarray)

If Lngarray (lngcount) >lngmax Then Lngmax=lngarray (lngcount) End If Next End Function Pairs For too long statements, you must use the continuation line, the continuation of the position to have a clear meaning, example: sql = "SELECT [Code],[name]" from [Person] "_ &" WHERE [code] like ' 0 01% ' "&" and [code] like ' 2% '

If the parameter of the function is too long, it should also be continued, example:

'

' Increase inventory

' ProductCode Product number

' Spec length specification

' Color colors

' Patch whether to spell the ring

' Volumn plate number

' Ordinal Inventory order number

' Length

' Ischeck whether to audit the storage increase (otherwise to discard the audit out of the library increase) public Sub Adddetail (ProductCode as String, _ Spec as Double, _ Color As String, _ Patch as Boolean, _ volumn As String, _ Ordinal as Integ Er, _ Length as Double, _ Ischeck as Boolean)

4. Annotation Agreement

4.1 Annotation Quantity

The more detailed the program, the more careful the better.  Each variable declared in the program can be added with the best note translation, at least the variables used to compute or save the key data must be added to the annotation. For each logical piece of code that implements a basic function, it is best to add a simple note to the line above it. For each custom function, the size must be added to the annotation.

4.2 Format

The format of the note translation is as follows:

'******************************************************

'

Functions implemented by the function

' The meaning of parameter 1 of the function: XXXXX

' The meaning of parameter 2 of the function: XXXXX

'......

' The error message represented by the return value of the function: XXXXX

' function with a return value of 0 for execution success, for other values to indicate execution failure

'

' ****************************************************** public (Private) Function forexample (..... ............)  As Long ' ... ..... ..... ..... ..... ..... ..... ..... ..... ..... ....... ... End Function

At the top of each code module (form, class, module, control), you must write the code writer, code creation time, code modification time, and modification instructions. Example:

'

' Inventory modification Form

' Author XXXXXX

' Build date 2005-6-22

' Modification date 2005-6-23 modified person XXXXXX

' Increase the functionality that affects the final warehousing date when the inventory is modified

5. Program Design Agreement

1. The program starts with the main () function.

2. The same program can run only once on a single machine and can neither run multiple copies of the same program at the same time.

That is if app.previnstance = True Then End

3. The same logged-on user can only log on to the same system at the same time.

4. It is recommended to use a long variable instead of the integer type.

This reduces some data overflow errors and, on the WIN32 bit platform, the CPU handles 32-bit data faster than the 16-bit data.

5. Use the & operator when connecting strings to avoid using the + operator.

The following example using the + operator to connect may cause problems. For example: vntVar1 = "10.01" vntVar2 = 11vntResult = vntVar1 + vntVar2 ' vntresult = 21.01vntResult = vntVar1 & VntVar2 ' Vntresu lt = 10.0111

6. When generating long strings, use the underscore connection character to produce multiple lines of code, which makes it easy to read or debug strings.

This technique is especially useful when a message box (MSGBOX) or an input box (InputBox) is displayed, or when an SQL string is generated. For example:

Dim MSG as Stringmsg = "This is a paragraph, that'll be" _& "in the message box. The text is ' _& ' broken into several lines of code ' _& ' in the source code, making it easier ' _& ' for the P Rogrammer to read and Debug. " MsgBox MSG

Dim QRY as Stringqry = "SELECT *" _& "from the Titles" _& "WHERE [year published] > 1988" Titlesqry.sql = QRY

7. Do not give the type conversion work to VB to do automatically, and use the following types of conversion functions.

CBool (expression) cbyte (expression) CCur (expression) CDate (expression) CDbl (expression) CDec (expression) CInt (expres sion) CLng (expression) csng (expression) CStr (expression) CVar (expression) Val (expression)

8. Error handling (edit a function to handle all known errors)

Add the following code to the main () function or the main form load process:

'******************************************************

'

' Open error log file, close in Form_Unload ()

'

' ****************************************************** Dim Strexepath as String

If Right (App.Path, 1) = "\" Then strexepath = App.Path Else Strexepath = app.path & "\" End If

Interrlogfilehandle = FreeFile ()

The Open Strexepath + "Err.log" for Append Shared as Interrlogfilehandle adds the following code to the main form Exit Function: ' ****************************** ************************

'

' Turn off error log files

'

' ****************************************************** close #intErrLogFileHandle added in a module:

'******************************************************

'

' Write error log

'

'******************************************************

Public Sub Writeerrlogfile (ByVal strsub As String, ByVal Strerr as String) Print #intErrLogFileHandle, Date, Time, St Rsub, Strerr end Sub in each procedure or custom function, use the following system error capture mechanism: Public function forexample (...).         As Long on the Error Goto funcerror forexample=true .............. ............... ........ Exit Function funcerror:forexample=false writeerrlogfile "forexample", "Error Number:" & Err.Number &, Error Source: " & Err.Source &, error description: "& Err.Description MsgBox" ... ", vbcritical

' Here's a memory resource recycle work end Function

9. Form layout

The layout of each control within the window is recommended as follows: 1. All controls that are adjacent to the top, bottom, left, and right four edges of the form are 120 twips apart from the edge of the form, and the spacing between controls is: Related controls 60 twips, non-related controls 120 twips 3, Button control size is high 300 twips, long 〉=1200 twips , which is also the size of the operating system default button 4, the font of each control is recommended for the song Body fifth word

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.