少し、趣の変わった回答です。
Private Sub Text1_KeyPress(KeyAscii As Integer)
EditText KeyAscii, "INTEGER", 3
End Sub
これで、Text1には3桁の数字しか入力できません。
OSがWindows98までを想定した関数ですので多少XP版にするには手直しが必要です。
が、まあ、一々、テキストボックスの入力チェックルーチンを書くのも手間です。
このような関数を使うのも手です。
' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' 入力テキストボックスを編集する関数
' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Sub EditText(ByRef KeyAscii As Integer, ByVal ColType, ByVal MaxLength As Integer)
Dim I As Integer
Dim L As Integer
Dim R As Integer
Dim Del As Integer
Dim Text As String
Dim RStr As String
Dim Start As Integer
Dim Suji As Integer
Dim Uwagaki As Boolean
If TypeOf Screen.ActiveControl Is TextBox Then
Select Case KeyAscii
Case 0, 3, 8, 13, 24, 26, 27
Case 22
'Temp = Clipboard.GetText(vbCFText)
'L = Len(Temp)
'For I = 1 To L
'EditText Asc(Mid(Temp, I, 1)), ColType
'Next I
Case Else
'Uwagaki = Screen.ActiveForm.ModeButton.Enabled
Uwagaki = True
Start = Screen.ActiveControl.SelStart
Text = Screen.ActiveControl.Text
If Uwagaki Then
'
' カーソル位置の文字を消すと、結果として上書きされます
'
L = Len(Text)
' 末尾以外のみ上書き処理
If Start < MaxLength Then
If Start < L Then
' 最低1文字は消去
' 全角入力で半角の上は2文字消去
Del = 1 + (LenB(Mid(Text, Start + 1, 1)) = 1) * (KeyAscii < 0)
' 上書き箇所より右の残存文字数を求める
R = L - Start - Del
If R > 0 Then
RStr = Right$(Text, R)
End If
End If
Text = Left$(Text, Start) & RStr
Else
MsgBox "定められた桁数以上は入力出来ません。"
KeyAscii = 0
End If
End If
If InStr(1, "INTEGER, SMALLINT, DECIMAL, MONEY", Trim(UCase(ColType)), vbTextCompare) > 0 Then
Suji = True
Select Case KeyAscii
Case Asc("-")
Suji = InStr(1, Text, "-", vbTextCompare) = 0 And Start = 0
Case Asc(".")
Suji = InStr(1, Text, ".", vbTextCompare) = 0
Case Is < Asc("0"), Is > Asc("9")
Suji = False
End Select
If Not Suji And KeyAscii <> 0 Then
MsgBox "数字以外の文字は入力出来ません!"
KeyAscii = 0
'Text = ""
'Start = 0
End If
End If
Screen.ActiveControl.Text = Text
Screen.ActiveControl.SelStart = Start
End Select
End If
End Sub
お礼
お世話になります。 数値以外の入力ですが自分で調べたら以下の方法で上手くいきました。アドバイスありがとうございます。 Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = vbKeyBack Then Exit Sub If Not Chr(KeyAscii) Like "[0-9]" Then KeyAscii = 0 MsgBox "数値以外です。" Else If Len(Text1.Text) >= 3 And _ ((KeyAscii >= Asc("A") And KeyAscii <= Asc("z")) _ Or (KeyAscii >= Asc("0") And KeyAscii <= Asc("9"))) Then MsgBox "桁数は3桁までです。", vbOKOnly + vbInformation, "情報" KeyAscii = 0 End If End If End Sub
補足
お世話になります。 ありがとうございます。うまくいきました。 それからもう一つ要望なのですが数値以外の値を入力した時は「数値以外は入力できません。」というメッセージをを出し入力受け付けないようにしたいのですがどうすれば良いでしょうか? 以下のように考えてみたのですが上手くいきません。よろしくお願い致します。 Private Sub Text1_KeyPress(KeyAscii As Integer) If IsNumeric(Right(Text1.Text, 1)) = False Then MsgBox "数値以外です。" KeyAscii = 0 Exit Sub End If If Len(Text1.Text) >= 3 And _ ((KeyAscii >= Asc("A") And KeyAscii <= Asc("z")) _ Or (KeyAscii >= Asc("0") And KeyAscii <= Asc("9"))) Then MsgBox "桁数は3桁までです。", vbOKOnly + vbInformation, "情報" KeyAscii = 0 End If End Sub ※1桁目が数値以外だと受け付けませんが1桁目が数値で2桁目が数値以外ならそれは受け付けずに2桁目から 再度入力できるようにしたいと思っています。 よろしくお願い致します。