编程风格 好代码的逻辑
- 缩进 -过程通常包含几个部分。 可能会有一个部分用于错误处理代码,用于重复操作的代码行组,在某些条件下但在其他条件下不执行的替代语句组等。缩进是识别代码段的一种有用方法。 尽管它对编译器绝对没有影响,但确实使您的代码更易于阅读和理解。
Do movespot = movespot / 2 MyRS.Move (movespot) If StrComp(MyRS![LastName], searchadv) < 1 Then ElseIf StrComp(MyRS![LastName], searchadv) = 0 Then MsgBox "Exact Match" Else MyRS.Move (0 - movespot) If Not MyRS.EOF Or MyRS.BOF Then MyRS.MoveFirst End If End If Loop Until movespot < 2
- 使用注释 -在创建代码时,过程语句的目的和逻辑可能显而易见。 几天或几周后,这种逻辑对您来说可能是难以捉摸的,而对其他人则完全令人困惑。 通过注释代码来节省您自己和其他人的时间和精力。 在过程的开头应包含注释,以描述过程的目的,参数以及函数过程返回的值。 不必注释每一行代码,事实上,它太右下角了,但是您至少应包括一条注释,以解释每组语句的逻辑。 要指定注释行,请在前面加上撇号。 默认情况下,VB编辑器会将注释行更改为绿色。
'Make sure to 1st set a Reference to the Microsoft Excel XX.X Object Library Dim objExcel As Excel.Application Set objExcel = CreateObject("Excel.Application")
- 使用命名约定 -为命名在应用程序中创建的对象建立一致的模式非常重要。 通过为过程,对象,常量和变量选择正确,一致地应用的命名约定,您的VBA代码变得更加自文档化并且更易于理解。
Dim strLastName As String Dim lngZipCode As Long Dim blnFoundFile As Boolean Dim dteBirthDate As Date Dim rstNew As Recordset Dim dbNorthwind As Database Dim dblPie As Double Dim astrEmployees(100) 'an Array of Strings fExtractMiddleInitial(strFullName As String) As String 'Function
- 对每个语句使用单独的行 -尽管您可以在一行中将多个用冒号分隔的语句串在一起,但是请不要这样做。 压缩代码的好处远远超过了读取代码的难度增加。
Do While Not MyRS.EOF 'Avoid 2 statements on a single line Debug.Print MyRS![LastName]: MyRS.MoveNext Loop
- 使用换行符 -您可能已经注意到,“模块窗口”没有自动换行功能。 如果输入的语句很长,则可以使用由空格和下划线(_)组成的换行符来自行包装该语句。 如果您不使用此字符将一行换成长行,则需要使用水平滚动条来查看语句的各个部分。 您不能使用换行符将字符串表达式包装到另一行; 取而代之的是,您可以将字符串分成较小的部分并将其连接起来。
Dim strMsg As String 'Instead of this 'strMsg = "The rules of Referential Integrity have been violated. You have made an attempt to enter a Training Record for an Employee in the Training Table when this individual doesn't exist in the Parent (Employees) Table. Enter a valid Employee Record first, then proceed" 'Use this syntax strMsg = "The rules of Referential Integrity have been violated. You have made an " & _ "attempt to enter a Training Record for an Employee in the Training Table " & _ "when this individual doesn't exist in the Parent (Employees) Table. Enter " & _ "a valid Employee Record first, then proceed" MsgBox strMsg, vbExclamation, "Referential Integrity Violation"
- 在过程开始时声明变量和常量 -通过在过程开始时对所有声明语句进行分组,您可以一目了然地看到这些常数和变量,而无需遍历过程代码来查找它们。
Private Sub_SomeButton_Click() Dim dbMyDB As Database, rstMyRS As Recordset, intNoOfRecords As Long Dim intCounter As Integer, tdfNew As DAO.TableDef, fldOld As DAO.Field End Sub
翻译自: https://bytes.com/topic/access/insights/642498-6-pack-good-programming-style-hints
编程风格 好代码的逻辑