Calculate date based on the date in text box - excel

I have a userform with few text boxes.
I would like to calculate a date based on the date put on text box1.
E.g. on text box 1 you enter today's date.
I want to calculate a date 5 years from today on textbox 2.
Private Sub TextBox1_AfterUpdate()
TextBox2.Value = Format(Val(TextBox1.Value) + 1825, "DD/MM/YYYY")
End Sub

Suggestions:
Use DateValue or CDate instead of Val.
Use DateAdd instead of the hard-coded 1825.
Format(DateAdd("yyyy", 5, CDate(TextBox1.Value)),"dd/mm/yyyy")

Private Sub TextBox1_AfterUpdate()
TextBox2.Value = Format(CDate(TextBox1.Value) + 1825, "DD/MM/YYYY")
End Sub

Use DatePicker you deminish chances of incorrect input and amount of needed error handlers and issues when user has US instead of UK format, or the other way around.
For using date use Dim myDate as Date: myDate = DateSerial(year, month, day) <- all as integers, whenever handled by code, this also would protect you from format differences.
Never set hard date format into inputs.

Related

Problem with value as date and format as text in cell

I'm writing a Macro where I need two things in one of the column ranges:
a) Cell values must be the date of the next day in the dd/mm/yyyy format;
b) Cell Format must be text
I keep running into the problem of the date format being changed to mm/dd/yyyy.
Default excel format for the vba function date is dd/mm/yyyy ,since my excel language is set to Portuguese.
By running:
Sub format()
Range("A1").Value = Date + 1
End Sub
I get the value 11/02/2023, date format, which is expected. But if I run:
Sub format2()
Range("A1").NumberFormat = "#"
Range("A1").Value = Date + 1
End Sub
The output is 02/11/2023 in text, in the mm/dd/yyyy format. I'd like to understand why this would even happen
Same thing happens for me. Not sure why but you can achieve what you want by doing:
Sub format2()
Range("A1").NumberFormat = "#"
Range("A1").Value = format(Date + 1, "dd\/mm\/yyyy")
End Sub
This will result in the cell being formatted as text in format "dd/mm/yyyy".
If you wanted the same format but actually formatted as date, you should do this:
Sub format2()
Range("A1").NumberFormat = "dd\/mm\/yyyy;#"
Range("A1").Value = Date + 1
End Sub
The backslashes are there because excel (at least on my system) considers the forward slash a substitute for default separator and replaces it with hyphens, which are my actual default separators.
I'd like to credit this answer for the last point (escaping the forward slashes): https://stackoverflow.com/a/8527762/9852011

Excel VBA set date to nearest day, is there a better way to do it?

Recently I needed to set some dates in Excel to the nearest Wednesday for a scheduling process.
I found some answers here in stackoverflow and other sites but none were giving the desired result at all times. So, I wrote a little sub to achieve this for any day you need, but it got me wondering if there was a better way to achieve this, if not then I hope you find it helpful.
EDIT: This sub is part of a large process run by a macro by clicking a custom ribbon button, the input dates come from an array, therefore, I have to use vba to change them.
Here is the matrix with results:
And the code is this:
Sub SetNextWed()
Range("A6").Activate
Do Until ActiveCell.Value = ""
SetToNextDate ActiveCell.Value, vbWednesday, 2
ActiveCell.Offset(1, 0).Activate
Loop
End Sub
Sub SetToNextDate(MyDate As Date, DayOfWeek As Integer, Column As Integer)
Dim dNext_Wednesday As Date
dNext_Wednesday = MyDate
Select Case Weekday(MyDate)
Case DayOfWeek
dNext_Wednesday = MyDate
Case Else
dNext_Wednesday = MyDate + DayOfWeek - Weekday(MyDate)
If MyDate > dNext_Wednesday Then
dNext_Wednesday = MyDate + ((DayOfWeek + 7) - Weekday(MyDate))
End If
End Select
I've tried this solutions:
https://vbaf1.com/date-time/next-wednesday-date/
https://www.mrexcel.com/board/threads/determine-date-of-next-and-most-recent-monday-vba.983467/
How do I find out what the Date is for Next Saturday or the current Saturday?
In Excel, dates are just numbers, and the date number modulo 7 gives you the day of the week, with 0 as Saturday through 6 as Friday. So you don't need VBA. The following cell formula calculates the Wednesday date you desire: =7*INT((A1+2)/7)+4, assuming the original date is in A1.

Cannot convert date string to datevalue in Excel

I have some dates in a string in a column.
Because the format seems to be M/DD/YYYY I sometimes get a VALUE error when using DATEVALUE.
How can I convert a column to make sure all dates are correct.
For example, the following 2 cells
9/29/2006 12:49:58.956 AM DATEVALUE gives an error
9/12/2008 5:36:59.356 PM DATEVALUE converts to 39791
You need to select the range (just one colunm) with the dates... Go to:
(in Excel 2010)
Data >>> Text to Columns
Inside the dialog box select:
Delimited >>> Next
Just select Tab checkbox.
And heres is the magic!
You need to define the arrangement for your dates...
In the Date field:
Choose the what you need (as you say in your question is M/D/Y)
Destination field:
Make sure that is the same of the data you want to format.
And finish.
The problem you are having is probably that the data is getting interpreted as a general field, and shows up as, say 49:59.0 - which isn't text, which is what Datevalue() expects as input; for both inputs, Datevalue(CellID) words if you prepend the text with a ' - which ensures it is treated as text.
it seems that your system settings use dd/mm/yyyy for short date format. and datevalue function uses this settings, so its try to read the day from the first part of the string and the month from the second part. as in your example 9/29/2006 12:49:58.956 AM there is no month with 29 then it gives error, and in the second example it gives 39791 = 9 december 2008 and NOT 12 september 2008.
If you change the short date format in your system settings to mm/dd/yyyythen datevalue function will work correctly, but this not acceptable, so we need to replace month with day and day with month to get correct date.
I don't know if we can do this with Excel formula but we can do that simply with VBA.
So try this code:
Sub Test()
Dim d1 As Variant, d2 As Variant, td As Date
Dim Rng As Range, CL As Range
Set Rng = Range("A1:A2") ' change this to your range
For Each CL In Rng
d1 = Split(CL.Value, " ")
d2 = Split(d1(0), "/")
td = DateSerial(d2(2), d2(0), d2(1))
CL.Offset(0, 1) = td
CL.Offset(0, 1).NumberFormat = "mm/dd/yyyy" ' change the Date format as you need
'CL.Offset(0, 1).NumberFormat = "dd/mm/yyyy"
Next
End Sub

Date format is switching month and day

Could you please someone can help me on how to change the date formatting cause i use the following code and instead of today's date it gives me august date. I mean it takes the date of my laptop (08-sep-2015) and it returns on the excel cell (09-Aug-2015).
Private Sub UserForm_Initialize()
'testing variable
'Dim LValue As String
'LValue = Format(#4/17/2004#, "Long Date")
'close testing variable
Me.tbDate = Date
'fill combobox
For Each cell In [cartridges]
Me.cmbCartridges.AddItem cell
Next cell
End Sub
The part that i exclude form the code is a test i made for a solution i found over the internet.
Also the text box that i want to present the date has the following code
ssheet.Cells(nr, 1) = CDate(Me.tbDate)
I found this and sorted my issue. Now everything its working like a charm.
Me.tbDate = Format(Date, "dd/mm/yyyy")
I resolved my issue with this code. I intentionally formated the cell the wrong way (excel default) and then formated it as I needed.
For j = 0 To LISTBOXNAME.ListCount - 1
LISTBOXNAME.List(j) = Format(DateValue(LISTBOXNAME.List(j)), "m/d/yyyy")
LISTBOXNAME.List(j) = Format(DateValue(LISTBOXNAME.List(j)), "dd.mm.yyyy")
Next j

excel vba need date as integer value like in excels datevalue()

I try to get a date that is available as a string in "DD.MM.YYYY" fashion, changed to the value that excel normally applies to dates.
I tried CDbl(strDate) as was suggested a lot. But instead of giving back 42023 as =DATVALUE("19.01.2015") does, in my case it returns 19012015.
strDate = "19.01.2015"
MsgBox CDbl(strDate)
How can I change that?
thanks
Try changing the full-stops (periods) to slashes, then convert to date, then convert to double.
Watch out for regional variations in date formatting though - not sure how it will affect the result - test with a date such as 01/02/2015 and see if it returns 1st Feb or 2nd Jan.
Sub test()
Dim strdate As String
strdate = "19.01.2015"
MsgBox CDbl(CDate(Replace(strdate, ".", "/")))
End Sub

Resources