プロが教える店舗&オフィスのセキュリティ対策術

Version 6.0 です。

テキストボックスに入力された値の中に任意の文字があるかどうかを判断する関数というのはあるでしょうか?InStrとかでやってみたのですが、If文を繰り返すことになってしまい、見難い状況です。

2つのテキストボックスに年月を入力させ、
"yyyymm"、"yyyym"、"yyyy/mm"、"yyyy/m"
が入力可。入力した文字列に"/"があるかないかを判断し、あればそのままでIsDateでチェック。なければ、"/"を入れてIsDateでチェック、とさせたいです。

何か簡単なコードの書き方等あれば、ぜひ教えてください。分かり難いところがあれば、補足します。よろしくお願いします。

A 回答 (3件)

こんにちは。

maruru01です。

ちょっと長い気もしますが。
フォーム上に、Text1とCommand1があるとします。


Private Sub Command1_Click()

  Dim temp As String
  Dim p As Long
  Dim pp As Long
  Dim ppp As Long

  temp = Text1.Text
  p = InStr(1, temp, "/", vbTextCompare)
  If p <> 5 And p <> 0 Then
    MsgBox "区切り記号位置エラー"
    Exit Sub
  End If
  pp = Len(temp)
  temp = Replace(temp, "/", "", , , vbTextCompare)
  ppp = Len(temp)
  If pp - ppp > 1 Then
    MsgBox "区切り記号位置エラー"
    Exit Sub
  End If
  If Len(temp) < 5 Or Len(temp) > 6 Then
    MsgBox "桁数エラー"
    Exit Sub
  End If
  temp = Left(temp, 4) & "/" & Mid(temp, 5)
  If IsDate(temp) Then
    MsgBox "日付データ" & vbCrLf & Format(temp, "yyyy/mm")
  Else
    MsgBox "日付と認識出来ない"
  End If

End Sub


あとは、適当に応用して下さい。
    • good
    • 0
この回答へのお礼

お礼が遅くなってしまって申し訳ありませんでした。
そして、早速の回答ありがとうございました。

やはりたくさんのIf文で判断していくことになるんですね。
教えていただいたコードを元に書いてみたいと思います。

ありがとうございました。

お礼日時:2003/10/21 18:13

#2のものです。



ちょっとまちがってましたね。
修正版です。


Dim wstr As String
Dim wYear As Integer
Dim wMonth As Integer
Dim wDate() As String

wstr = txtDate.Text

'入力チェック
If IsNumeric(Replace(wstr, "/", "")) = False Then
MsgBox "入力ミス"
GoTo Error
End If
If Len(wstr) < 5 Then
MsgBox "入力ミス"
GoTo Error
End If

'年/月取得
'/が存在しない
If InStr(1, wstr, "/") = 0 Then
wYear = CInt(Mid(wstr, 1, 4))
wMonth = CInt(Mid(wstr, 5))
'/が存在する
Else
wDate = Split(wstr, "/")
If wDate(0) = "" Then
MsgBox "年入力ミス"
GoTo Error
End If
If wDate(1) = "" Then
MsgBox "月入力ミス"
GoTo Error
End If
wYear = CInt(wDate(0))
wMonth = CInt(wDate(1))
End If

If IsDate(wYear & "/" & wMonth) = False Then
MsgBox "年月入力ミス"
End If
    • good
    • 0
この回答へのお礼

二度もありがとうございます。
そして、お礼が遅くなってしまって申し訳ありません。

教えていただいたコードを元に書いてみたいと思います。

お礼日時:2003/10/21 18:15

任意の箇所に"/"を入れるわけではないですが、年と月を分離することで、日付チェックが可能だと思います。



以下のコードを参考ください。

Dim wstr as String
Dim wYear as Integer
Dim wMonth as Integer
Dim wDate() as String

wstr = txtDate.text

'入力チェック
If IsNumeric(wstr) = False Then
MsgBox "入力ミス"
GoTo Error
End If
If Len(wstr) < 5 Then
MsgBox "入力ミス"
GoTo Error
End If

'年/月取得
'/が存在しない
If InStr(1, wstr, "/") = 0 Then
wYear = CInt(Mid(wstr, 1, 4))
wMonth = CInt(Mid(wstr, 5))
'/が存在する
Else
wDate = Split(wstr, "/")

wYear = CInt(wDate(0))
wMonth = CInt(wDate(1))
End If

If IsDate(wYear & "/" & wMonth) = False Then
MsgBox "年月入力ミス"
End If
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!