Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting from a date in VBA?

Tags:

excel

vba

I'm having big problems doing operation with the date in Excel VBA. I have a form that has a textbox where the user will enter the date. The problem is that he may enter it in different formats (eg, 1.08.2011 for 1st of August, or 8/1/11 for the same day). Now what I want to do is to subtract some days from that date that he enters in the TextBox. I had to success so far and I don't know how to do it. I tried something like this

Format((Format(Me.datalivrare.Value, "dd.mm.yyy") - 4), "dd.mm.yyyy")

Where datalivrare is that textbox where the user enters the date and 4 is the number of days I want to subtract from that date... and I want the format to always be dd.mm.yyyy no matter what they enter in that textbox.

like image 584
Andrei Ion Avatar asked Aug 08 '11 18:08

Andrei Ion


2 Answers

I suggest looking at the DateAdd function for VBA

http://www.techonthenet.com/excel/formulas/dateadd.php

http://office.microsoft.com/en-us/access-help/dateadd-function-HA001228810.aspx

You could do the following:

Format(DateAdd("d", -4, CDate(Me.datalivrare.Value)), "dd.mm.yyyy")
like image 153
Taryn Avatar answered Sep 21 '22 13:09

Taryn


First cast to Date, then subtract days, then format appropriately:

Format(DateAdd("d", -4, CDate(Me.datalivrare.Value)), "dd.mm.yyyy")
like image 37
Lance Roberts Avatar answered Sep 21 '22 13:09

Lance Roberts