0

私は3つの異なるPrivateSub関数を作成ましたが、これらはすべて同じことを行います。PrivateSubtxt_noRooms_KeyPressPrivateSub txt_length_KeyPressは、ユーザーが参照テキストフィールドに値1〜9のみを入力できるようにしますが、 PrivateSubtxt_studentNo_KeyPressではユーザーが入力できます。参照されるテキストフィールドに0〜9の値を入力します。

これらの3つの関数をマージして、参照されたセルを引き続きサポートし、同じ条件を維持する方法はありますか?コードをより効率的にするためにこれを行いたいと思います。

Private Sub txt_noRooms_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_noRooms
Select Case KeyAscii
    Case Asc("1") To Asc("9")
    Case Asc("-")
        If InStr(1, Me.txt_noRooms.Text, "-") > 0 Or Me.txt_noRooms.SelStart > 0 Then
            KeyAscii = 0
        End If
    Case Asc(".")
        If InStr(1, Me.txt_noRooms.Text, ".") > 0 Then
            KeyAscii = 0
        End If
    Case Else
        KeyAscii = 0
End Select
End Sub


Private Sub txt_length_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)   
' Restrict entry to txt_length
Select Case KeyAscii
    Case Asc("1") To Asc("9")
    Case Asc("-")
        If InStr(1, Me.txt_length.Text, "-") > 0 Or Me.txt_length.SelStart > 0 Then
            KeyAscii = 0
        End If
    Case Asc(".")
        If InStr(1, Me.txt_length.Text, ".") > 0 Then
            KeyAscii = 0
        End If
    Case Else
        KeyAscii = 0
End Select
End Sub


Private Sub txt_studentNo_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_studentNo
Select Case KeyAscii
    Case Asc("0") To Asc("9")
    Case Asc("-")
        If InStr(1, Me.txt_studentNo.Text, "-") > 0 Or Me.txt_studentNo.SelStart > 0 Then
            KeyAscii = 0
        End If
    Case Asc(".")
        If InStr(1, Me.txt_studentNo.Text, ".") > 0 Then
            KeyAscii = 0
        End If
    Case Else
        KeyAscii = 0
End Select
End Sub
4

1 に答える 1

3

1つのプライベート関数を設定し、キーを押すたびに呼び出すことができます。

  Private Sub txt_noRooms_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_noRooms
If bclearfield(CLng(KeyAscii), Me.txt_noRooms.Text, Me.txt_noRooms.selStart,"1")  Then KeyAscii = 0
End Sub


Private Sub txt_length_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_length
If bclearfield(CLng(KeyAscii), Me.txt_length.Text, Me.txt_length.selStart,"1") Then KeyAscii = 0
End Sub

Private Sub txt_studentNo_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_studentNo
If bclearfield(CLng(KeyAscii), Me.txt_studentNo.Text, Me.txt_studentNo.selStart,"0") Then KeyAscii = 0
End Sub

Private Function bClearField(KeyAscii As Long, sText As String, lSelStart As Long,sLowLimit as string) As boolean

bClearField=false
Select Case KeyAscii
    Case Asc(sLowLimit ) To Asc("9")
    Case Asc("-")
        If InStr(1, sText, "-") > 0 Or lSelStart > 0 Then
            bClearField=true
        End If
    Case Asc(".")
        If InStr(1, sText, ".") > 0 Then
            bClearField=true
        End If
    Case Else
        bClearField=true
End Select

End Function
于 2012-10-10T23:21:23.350 に答える