devxlogo

Change Dates With Plus and Minus Keys

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 = DateEnd SubPrivate Sub Text1_KeyPress(KeyAscii As Integer)	' Pass handling to generic routine.	KeyAscii = DateHandler(KeyAscii)End SubPrivate 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 FunctionErrorHandler:	DateHandler = 0	Exit FunctionEnd Function
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist