这篇博客是关于一些代码小细节的问题:
一、
If Not testtxt(txtResult.Text) Then
MsgBox "请输入分数", vbOKOnly + vbExclamation, "警告"
txtResult.SetFocus
Exit Sub
End If
解释:ExitSub '出错后,跳出过程,改正后,重新执行该过称 ,如果没有该句,将会继续向下执行 ,即使你没有改正错误
txtResult.SetFocus ExitSub 这两句话不可颠倒,因为VB是按顺序读代码的,如果颠倒了,Exit Sub過程到止結束, 位於該過程的後代碼將被忽略.。
二、
Public Function ExecuteSQL(ByVal Sql As String, msgstring As String) As ADODB.Recordset
''定义查询执行函数为记录集
'一个自定义的函数,这个函数是利用传入的sql查询字符串,返回ado记录集
Dim cnn As ADODB.Connection '定义数据库连接变 ADODB是动态数据链接对象
Dim rst As ADODB.Recordset '定义一个记录集对象
Dim stokens() As String '定义数组变量为字符串类型
On Error GoTo executesql_error '发生错误转到executesql_error
stokens = Split(Sql) '’以空格为标识符 拆分sql语句
Set cnn = New ADODB.Connection '建立数据库连接对象
cnn.Open ConnectString '连接数据库
If InStr("INSERT,DELETE,UPDATE", UCase$(stokens(0))) Then
cnn.Execute Sql
msgstring = stokens(0) & "query successful"
Else
Set rst = New ADODB.Recordset
rst.Open Trim$(Sql), cnn, adOpenKeyset, adLockOptimistic
Set ExecuteSQL = rst '执行数据库查询
msgstring = "查询到" & rst.RecordCount & "记录"
End If
executesql_exit: 'ExecuteSQL_Exit:后的语句用于清除变量对象
Set rst = Nothing
Set cnn = Nothing
Exit Function
end function
'(由于vb是顺序执行,所以在ExecuteSQL_Error之前还有一个end function
'使程序在没有错误的时候不会执行ExecuteSQL_Error后的内容
executesql_error:
msgstring = "查询错误:" & Err.Description
Resume executesql_exit
End Function
解释: 'if()then是判断stokens中(通过splite将sql代码拆分而来)有没有 NSERT,DELETE,UPDATE这三个字符
'如果有的话使用Execute方法来执行
'如果没有的话就用recordset的open方法来返回一个recordset对象
'然后使用Set ExecuteSQL = rst 将recordset对象设置给函数ExecuteSQL(返回值)
三、
Public Function testtxt(txt As String) As Boolean
If Trim(txt) = "" Then
testtxt = False
Else
testtxt = True
End If
End Function
解释:这是一个自定义函数,返回值是boolean,参数是txt 的字符串