这是一家公司软件部规定的VB组代码撰写暂行约定。对于VB项目的协同开发有一定的帮助和指导。
一、变量和对象
程序中的变量遵循匈牙利表示法,即“前缀+变量含义”,变量的含义为一个或多个英文单词,每个单词的第一个字母大写,不要用汉语拼音代替。变量前缀为三个小写字母示意其类型,所需添加的前缀遵循微软在MSDN中的建议。列表如下:
基本数据类型
变量类型 | 前缀 | 示例 |
Boolean | bln | blnFound |
Byte | byt | bytRasterData |
Collection object | col | colWidgets |
Currency | cur | curRevenue |
Date (Time) | dtm | dtmStart |
Double | dbl | dblTolerance |
Error | err | errOrderNum |
Integer | int | intQuantity |
Long | lng | lngDistance |
Object | obj | objCurrent |
Single | sng | sngAverage |
String | str | strFName |
User-defined type | udt | udtEmployee |
Variant | vnt | vntCheckSum |
控件或窗体、模块对象
控件类型 | 前缀 | 示例 |
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 (在过程中使用的类型未明的控件变量) | 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 |
数据库对象
数据库对象 | 前缀 | 示例 |
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 |
除此之外,还要对于一些不同的级别的变量加额外的前缀,举例如下:
级别 | 前缀 | 示例 |
全局变量 | g | gstrUserName |
模块级变量 | m | mblnCalcInProgress |
过程级变量 | None | dblVelocity |
对于用户使用type关键字定义的数据类型,在三个字母的前缀前再加u。例如:一个用户定义的叫Client类型的变量,其前缀为ucli。
关于变量使用方面,建议如下:
1、变量要先声明再使用(在窗体代码的第一行加上Option Explicit,来禁止未声明变量的调用,或者在菜单Tools->Options->Editor中选中Require Variable Declaration项。)
2、尽量使用Long型的变量来代替Integer类型,这样做可以减少一些数据溢出的错误,而且,在Win32平台上,CPU处理32位的数据比16位的数据速度更快。
3、尽量少用Variant变量,尽可能地给出每一个变量明确的类型
4、尽量不在API声明中使用As Any,如果遇到其默认的参数为As Any的情况,则针对每一个所需的参数类型声明该API函数,例如ReadFile函数默认的声明为:
Public Declare Function ReadFile Lib "kernel32" Alias "ReadFile" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As OVERLAPPED) As Long
小组成员须将其改为:
Public Declare Function ReadFileByt Lib "kernel32" Alias "ReadFile" (ByVal hFile As Long, lpBuffer As Byte, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As OVERLAPPED) As Long
Public Declare Function ReadFileInt Lib "kernel32" Alias "ReadFile" (ByVal hFile As Long, lpBuffer As Integer, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As OVERLAPPED) As Long
Public Declare Function ReadFileLng Lib "kernel32" Alias "ReadFile" (ByVal hFile As Long, lpBuffer As Long, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As OVERLAPPED) As Long
5、不要将类型转换的工作交给VB自动去做,而使用以下类型转换函数
CBool(expression)
CByte(expression)
CCur(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CSng(expression)
CStr(expression)
CVar(expression)
二、窗体布局
窗体内各个控件的布局,建议如下:
1、所有与窗体上、下、左、右四条边界相邻的控件与窗体的边缘相距120缇
2、各个控件之间的间距为:相关控件60缇,非相关控件120缇
3、按钮控件大小建议为高300缇,长1200缇,这也是操作系统默认按钮的大小
4、各个控件的字体建议为宋体五号字
三、代码
1、程序的启动对象
程序一率从Main()函数开始执行(选择菜单View->Project Explorer,在工程窗口内右键点击当前项目,选择菜单“… Properties”->General,在Startup Object下拉框中选择sub main)
2、代码缩进与间距
每个单位的代码缩进为一个TAB,非相关代码留一行空白的间隔,例如:
Private Function GetMax(Byref lngArray() As Long) As Long
GetMax=0
Dim lngMax As Long
Dim lngCount as long
For lngCount =0 to Ubound(lngArray)
If lngArray (lngCount)>lngMax Then
lngMax=lngArray(lngCount)
End If
Next
End Function
3、注译
程序的注译越详尽,越仔细越好。以下提及的,必须加注译。
程序中声明的每一个变量,能加上注译最好,至少用来运算或者保存关键数据的变量必须加上注译。
对于每一段逻辑上实现某个基本功能的几句代码,最好在其上一行加上简单注译。
对于每一个自定义的函数,不管大小都必须加上注译,而且注译的格式如下:
'******************************************************
'
'函数所实现的功能
'函数的参数1的含义:XXXXX
'函数的参数2的含义:XXXXX
'……
'函数返回值所代表的错误信息:XXXXX(函数尽可能声明为Function,不要声明为Sub,
'函数的返回值为0表示执行成功,为其它值表示执行失败)
'
'******************************************************
Public(Private) Function ForExample(……………………) As Long
'…………………………………………
End Function
4、错误处理(未定)
在Main()函数或主窗体Load过程中添加如下代码:
'******************************************************
'
'打开错误日志文件,在Form_Unload()中关闭
'
'******************************************************
Dim strExePath As String
If Right(App.Path, 1) = "" Then
strExePath = App.Path
Else
strExePath = App.Path & ""
End If
intErrLogFileHandle = FreeFile()
Open strExePath + "Err.log" For Append Shared As intErrLogFileHandle
在主窗体退出函数中添加如下代码:
'******************************************************
'
'关闭错误日志文件
'
'******************************************************
Close #intErrLogFileHandle
在某个Module中添加:
'******************************************************
'
'写入错误日志
'
'******************************************************
Public Sub WriteErrLogFile(ByVal strSub As String, ByVal strErr As String)
Print #intErrLogFileHandle, Date, Time, strSub, strErr
End Sub
在每个过程或自定义的函数中,使用如下的系统错误捕获机制:
Public Function ForExample(…………) As Long
On Error Goto FuncError
ForExample=True
………………………
………………………
Exit Function
FuncError:
ForExample=False
WriteErrLogFile " ForExample ", "错误号:" & Err.Number & ",错误源:" & Err.Source & ",错误描述:" & Err.Description
MsgBox "……… ", vbCritical
'在此作内存资源回收工作
End Function