重构代码-随笔(1)
原始代码:
If txtSchool.Text = "" Then
MsgBox "请输入注册单位!", vbInformation
CheckRegText = False
txtSchool.SetFocus
Exit Function
End If
MsgBox "请输入注册单位!", vbInformation
CheckRegText = False
txtSchool.SetFocus
Exit Function
End If
1:len(txtSchool.Text) 要比 txtSchool.Text=""快的多。
2:为txtSchool.Text加上Trim
3:去除txtSchool的重复。
结果:
1:StringIsEmpty函数
'判断字符串的长度是否为空
Public Function StringIsEmpty(ByRef sString As String) As Boolean
sString = Trim(sString)
StringIsEmpty = Len(sString) = 0
End Function
Public Function StringIsEmpty(ByRef sString As String) As Boolean
sString = Trim(sString)
StringIsEmpty = Len(sString) = 0
End Function
2:TextBoxIsEmpty函数
'文本框为空
Private Function TextBoxIsEmpty(oTextBox As TextBox, sMessage As String) AS Boolean
If StringIsEmpty(oTextBox.Text) Then
MsgBox sMessage, vbInformation
oTextBox.SetFocus
TextBoxIsEmpty = True
End If
End Function
Private Function TextBoxIsEmpty(oTextBox As TextBox, sMessage As String) AS Boolean
If StringIsEmpty(oTextBox.Text) Then
MsgBox sMessage, vbInformation
oTextBox.SetFocus
TextBoxIsEmpty = True
End If
End Function
3:最终效果
If TextBoxIsEmpty(txtPerson, "请输入注册人!") Then Exit Function
If TextBoxIsEmpty(txtConn, "请输入联系电话!") Then Exit Function
If TextBoxIsEmpty(txtSchool, "请输入注册单位!") Then Exit Function
If TextBoxIsEmpty(txtConn, "请输入联系电话!") Then Exit Function
If TextBoxIsEmpty(txtSchool, "请输入注册单位!") Then Exit Function