Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Beginner
Apr 6, 2000

Change Dates With Plus and Minus Keys

This simple piece of code saves a lot of headaches when it comes to altering dates. It allows you to use the plus and minus keys to increment and decrement date values easily. This example assumes there is a textbox named Text1 on a standard VB form:
 
Private Sub Form_Load()
	' Make sure that there is a valid date in Text1.
	Text1.Text = Date
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
	' Pass handling to generic routine.
	KeyAscii = DateHandler(KeyAscii)
End Sub

Private Function DateHandler(KeyAscii As _
	Integer) As Integer
	Dim nRet As Integer
	' This routine adds or subtracts days, based on the 
	' key pressed, from a date value found in the control 
	' represented by the form's ActiveControl property 
	' (usually a TextBox). The routine can be altered to 
	' add and subtract months and years too.
	On Error GoTo ErrorHandler
	' Constants which represent the '+' & '-' keys.
	Const KeyAdd = 43
	Const KeySubtract = 45
	' This constant is here because '+' & '=' are on the 
	' same key for most keyboards, but are sometimes inverted.
	Const KeyEquals = 61
' Determine the value of the key pressed, and 
	' take the necessary action.
	Select Case KeyAscii
		Case KeyAdd, KeyEquals
			Me.ActiveControl.Text = DateAdd("d", _
				1, Me.ActiveControl)
			nRet = 0
		Case KeySubtract
			Me.ActiveControl.Text = DateAdd("d", _
				-1, Me.ActiveControl)
			nRet = 0
		Case Else
			nRet = KeyAscii
	End Select
	' Move the start position to the end of the 
	' text for a cleaner look.
	If nRet = 0 Then
		Me.ActiveControl.SelStart = Len(Text1.Text)
	End If

	' Return a new KeyAscii value.
	DateHandler = nRet
	Exit Function

ErrorHandler:
	DateHandler = 0
	Exit Function
End Function
Sheppe Pharis
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date