If you've ever used Quicken, you've probably notice a handy little feature
in that program's date fields. You can press the [+] key to increment one
day, [-] to decrement one day, [PgUp] to increment one month, and [PgDn] to
decrement one month. In this tip, we'll show you how to emulate this
behavior with Visual Basic.
First, insert a text box on a form (txtDate). Set its text property to ""
and its Locked property to TRUE.
Now place the following code in the KeyDown event:
Private Sub txtDate_KeyDown(KeyCode As Integer, Shift As Integer)
'
' 107 = "+" KeyPad
' 109 = "-" KeyPad
' 187 = "+" (Actually this is the "=" key, same as "+" w/o the shift)
' 189 = "-"
' 33 = PgUp
' 34 = PgDn
'
Dim strYear As String
Dim strMonth As String
Dim strDay As String
'
If txtDate.Text = "" Then
txtDate.Text = Format(Now, "m/d/yyyy")
Exit Sub
End If
'
strYear = Format(txtDate.Text, "yyyy")
strMonth = Format(txtDate.Text, "mm")
strDay = Format(txtDate.Text, "dd")
'
Select Case KeyCode
Case 107, 187 ' add a day
txtDate.Text = Format(DateSerial(strYear, strMonth, strDay) +
1, "m/d/yyyy")
Case 109, 189 ' subtract a day
txtDate.Text = Format(DateSerial(strYear, strMonth, strDay) -
1, "m/d/yyyy")
Case 33 ' add a month
txtDate.Text = Format(DateSerial(strYear, strMonth + 1,
strDay), "m/d/yyyy")
Case 34 ' subtract a month
txtDate.Text = Format(DateSerial(strYear, strMonth - 1,
strDay), "m/d/yyyy")
End Select
'
End Sub
The one nasty thing about this is that if you have characters that are not
the characters usually in a date (i.e., 1-9, Monday, Tuesday, or /) you get
errors in the format command. To overcome this, I set the Locked property
to True. This way, the user can't actually type a character in the field,
but the KeyDown event still fires.
From--Mike Coleman, [Mike.Coleman@anixter.com]