减少代码冗余的方法

一:防止往下拉菜单输入:

Private Sub comboRelation2_KeyPress(KeyAscii As Integer) '防止输入字符
    KeyAscii = 0     'keyAscii=0?表示:取消本次输入的字符
End Sub

二:定义一个检查文本框是否为空的函数:

在模块中设函数:

Public Function testtxt(txt As String) As Boolean         '参数是txt,即文本框内容
    If Trim(txt) = "" Then
       testtxt = False
    Else
       testtxt = True
    End If
End Function

 调用函数判断是不是为空(不仅仅限用文本框)

If Not testtxt(Combouser.Text) Then
    MsgBox "请选择用户级别!", vbOKOnly + vbExclamation, "提示"
    Combouser.SetFocus
    Exit Sub
End If

三:设置case1:

Case1:
    With MSHFlexGrid1
        .Rows = 1
        .TextMatrix(0, 0) = "序列号"
        .TextMatrix(0, 1) = "教师"
        .TextMatrix(0, 2) = "级别"
        .TextMatrix(0, 3) = "注册日期"
        .TextMatrix(0, 4) = "注册时间"
        .TextMatrix(0, 5) = "注销日期"
        .TextMatrix(0, 6) = "注销时间"
        .TextMatrix(0, 7) = "机器名"
        .TextMatrix(0, 8) = "状态"
    End With

在同一个事件下面直接调用:GoTo Case1

四:限制特殊字符输入:

在模块中定义这个函数:

Public Function IsNumber(KeyAscii As Integer) As Integer
    Select Case KeyAscii
        Case 48 To 57    '只能输入数字
        Case 65 To 90    '只能输入大写字母
        Case 97 To 122   '只能输入小写字母
        Case 8           '只能输入退格
        Case Else       
        KeyAscii = 0     '无效
    End Select
        If Len(txtID) >= 3 Then    
           txtID.Text = ""  
           KeyAscii = 0    '输入字符清零
           MsgBox "输入字符位数过长", vbOKCancel, "提示"
        End If
End Function

在窗体中调用函数:

Private Sub txtid_KeyPress(KeyAscii As Integer)
Call IsNumber(KeyAscii)
End Sub

不能输入特殊字符,也不能超过三个数。

猜你喜欢

转载自blog.csdn.net/Ciel_Y/article/details/82924351