change the date format in a text box - excel

A text box in a user form has the vba below in order to paste the date in column D on my worksheet. I need the format of the date to be pasted as follows: "YYYY/MM/DD" exactly in this order.
However at the moment the code below pastes the date "DD/MM/YYYY". Am i missing something? thanks
.Cells(lRow, 4).Value = Me.txtDate.Value
.Cells(lRow, 4).NumberFormat = "YYYY/MM/DD"

A textbox contains a String. A date-formatted cell contains a Date (if you want Excel to understand it as a date anyway). You're missing a conversion.
Dim dateValue As Date
dateValue = ToDate(Me.txtDate.Value)
.Cells(lRow, 4).Value = dateValue
.Cells(lRow, 4).NumberFormat = "yyyy/MM/dd"
Where ToDate would be a function that takes a String and returns a Date. There are many ways to go about this, and you'll want to handle the situation where the provided string isn't a valid date.
Here's one way:
Private Function ToDate(ByVal value As String) As Date
ToDate = DateValue(value) 'raises error 13 "type mismatch" if invalid
End Function
If that's good enough, and only needed in one place, then you could inline it:
.Cells(lRow, 4).Value = DateValue(Me.txtDate.Value)
.Cells(lRow, 4).NumberFormat = "yyyy/MM/dd"

Related

CDATE VBA gives out 12:00:00 AM instead of date

I am trying to convert the date format of my cells as the csv format they are delivered in shows a date but excel doesn't recognize it as a date (it shows "Standard" as format and the dates are aligned on the left, hence not dates in excel).
Dim lr11 As Integer
Dim dates11 As Date
lr11 = WS1.Cells(WS1.Rows.Count, "C").End(xlUp).row
For dates11 = 2 To lr11
WS1.Cells(dates11, 3).Value = CDate(Cells(dates11, 3).Value)
Next dates11
The above code sometimes works in a Test Sub() but when used in my main Sub, I always get "12:00:00 AM" in all cells instead of dates.
What am I doing wrong?
Thanks!
If you have strings that look like dates in the format DD.MM.YYYY you can split them and create a numeric date using DateSerial like below:
Option Explicit
Public Function ConvertStringDDMMYYYYtoDate(ByVal InputString As String) As Date
Dim RetVal As Date
Dim Parts() As String
Parts = Split(InputString, ".")
If UBound(Parts) = 2 Then
RetVal = DateSerial(Parts(2), Parts(1), Parts(0))
If Not Format$(RetVal, "DD.MM.YYYY") = InputString Then
MsgBox "Input String is not a real date", vbCritical
RetVal = 0
End If
End If
ConvertStringDDMMYYYYtoDate = RetVal
End Function
Then use it like
For dates11 = 2 To lr11
WS1.Cells(dates11, 3).Value = ConvertStringDDMMYYYYtoDate(WS1.Cells(dates11, 3).Value)
WS1.Cells(dates11, 3).NumberFormat = "DD.MM.YYYY" ' format it however you like it to look like
Next dates11

Date function and update back issue

I have a two part issue regarding the same item. I have built a contracts management style system that relies on a userform to populate the worksheet and then another userform to recall the data from that sheet. This bit works perfectly. However, there is a 'start date' and 'end date' part that transfers from the userform to the worksheet.
Problem 1:
When the date is entered in dd/mm/yyyy and the 'dd' part is 1-12, it translates to US format for the date. For 'dd' values 13-31, it works fine. I have used format date code and this makes no difference.
Problem 2:
On the userform, I have an 'update' command button that overwrites any changed data back to the correct row on the excel sheet. If the date gets updated (i.e. 'end date' extended) this just returns 'FALSE' back to the cell. When I reload the contract back into the userform, it shows 31/12/1899.
Please can anyone help on any of the above?
This is the snip of the code for writing the dates for a new contract
ws.Cells(Lastrow + 1, 18).Value = TextBox18.Value
ws.Cells(Lastrow + 1, 21).Value = TextBox19.Value
This is the snip of the code for updating from the userform back to the excel sheet
Cells(rowselect, 18) = Me.TextBox18.Value = Format(TextBox18.Text, "mm/dd/yyyy")
Cells(rowselect, 21) = Me.TextBox19.Value = Format(TextBox19.Text, "mm/dd/yyyy")
I have searched many posts on here and none of the things I have tried are any better.
Thank you in advance.
For Problem 1:
If you know that the TextBox always has a date in UK-style dd/mm/yyyy, then YOU should take control of how the cell gets setup rather than relying on Excel to decide. Try code like:
arr = Split(TextBox18.Value, "/")
Cells(1, 1).Value = DateSerial(arr(2), arr(1), arr(0))
Cells(1, 1).NumberFormat = "dd mmmm yyyy"
and assuming that the TextBox gives 10/1/2021, then the result would be:
For Problem 2:
In some languages:
alpha = beta = gamma
would "daisy-chain" like:
beta = gamma
alpha = beta
VBA does not work that way. VBA sees:
alpha = (beta = gamma)
and evaluates (beta = gamma) as a Boolean; True if beta equals gamma, otherwise False
thanks for your help. I managed to fix this problem with your help to the following,
Private Sub TextBox18_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
arr = Split(TextBox18.Value, "/")
Dim dtDate As Date
dtDate = DateSerial(arr(2), arr(1), arr(0))
Me.TextBox18.Value = Format(dtDate, "dd mmmm yyyy")
End Sub
This cures the issue with the date not swapping to US as the date auto-updates in the textbox to Long Date Format.
The update issue I had to use three seperate input boxes for day, month and year and have VB put them together before updating the cell.
Thanks once again for your help.

Date Field Mixed (Date and Text) Formatting

I've had a look around and can't find an actual answer to this.
I have a .csv to download every day. In it includes a text field 7+2 digits long. The 7 digits are in format CYYMMDD and the 2 digits are blank spaces.
This would be today's date: "1190729 " (without the quotes)
I've tried about 20 ways to convert this to a regular date, but I can't get every record to update properly
So far
The QueryTable uses type 2 (Text)
I =TRIM the text, place it back in the same location
I change the text into a recognisable date
"Paste as Text"
Then I get the same thing every time. Any date where the DAY is 13 or more, is a text field. 12 and under is a date field
The best way to fix it is to F2 but this is meant to be a totally automated report
I have tried changing dd/mm/yyyy to every other version I can think of (as for my excel m/d/yyyy is the default)
I've also tried moving .Value = .Value to the bottom, putting it in twice etc. but to no avail
Private Sub CopyDateTime(ByVal lastRowBeforeImport As Long)
Dim ws As Worksheet, ws2 As Worksheet
Dim tempsheet As String
Dim lastRowAfterImport, lastRowTemp
Set ws = Worksheets("Report")
'Bottom populated cell of Column "B"
lastRowAfterImport = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
tempsheet = "temp"
Worksheets.Add
ActiveSheet.Name = tempsheet
Set ws2 = Worksheets("temp")
With ws.Range(ws.Cells(lastRowBeforeImport, 5), ws.Cells(lastRowAfterImport, 6))
'Copy new date and time to tempsheet'
.Copy Destination:=ws2.Range("A1")
End With
lastRowTemp = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row
With ws2.Range(Cells(1, 3), Cells(lastRowTemp, 3))
.FormulaR1C1 = "=TRIM(RC[-2])"
.Value = .Value
.Copy Destination:=ws2.Range("A1")
.Delete
End With
With ws2.Range(Cells(1, 3), Cells(lastRowTemp, 3))
.FormulaR1C1 = "=RIGHT(RC[-2],2)&""/""&MID(RC[-2],4,2)&""/20""&MID(RC[-2],2,2)"
.Value = .Value
.NumberFormat = "dd/mm/yyyy"
End With
With ws2.Cells(1, 4)
.FormulaR1C1 = "=MID(TEXT(RC[-2],""000000""),3,2)&"":""&LEFT(TEXT(RC[-2],""000000""),2)&"":""&RIGHT(RC[-2],2)"
End With
'Delete tempsheet'
Application.DisplayAlerts = False
'Worksheets(tempsheet).Delete
Application.DisplayAlerts = True
End Sub
If you have "1190729 " in A2 then the formula
=DATE(2000+(MID(A2,2,2)),(MID(A2,4,2)),(RIGHT(TRIM(A2),2)))
will produce the date 29th July 2019 in your current date format
From MSDN:
Date variables are stored as IEEE 64-bit (8-byte) floating-point
numbers that represent dates ranging from 1 January 100, to 31
December 9999, and times from 0:00:00 to 23:59:59.
Your VBA function may parse well string formats from CSV, but you are creating a string value which is not a proper Excel data type for dates.
Use =DATEVALUE function to convert the string representation of the DATE (ex. 29/7/2019) to the actual Excel date.
For example in your case: cell.Value = DATEVALUE(TRIM(RC[-2]))
Once in the proper data type, you can change the date format using the NumberFormat property.
More about DATEVALUE from MSDN.

Excel Date/Time Lookup Error

I have two columns of 15 minute date/time interval data. One is formatted in 24-hour time and the other 12-hour. These come from two different sources, and reformatting the source data is not an option. All of these intervals are showing as exact matches (even as values), but when I use a lookup formula (INDEX/MATCH & VLOOKUP) or even VBA, a match for every third interval is not being identified. I have attached sample pictures with formulas as well as my code below. Thanks in advance!
Sub MatchTest()
Dim i As Integer
For i = 2 To 22
If CDate(Cells(i, 1).Value) = CDate(Cells(i, 3).Value) Then
Cells(i, 8) = Cells(i, 2)
ActiveCell.Offset(1, 0).Select
Else:
Cells(i, 8) = "NA"
ActiveCell.Offset(1, 0).Select
End If
Next i
End Sub
Instead of Cdate, Timevalue and Datevalue can be used can be used. The TIMEVALUE function returns a serial number of a time. The DATEVALUE function converts a date that is stored as text to a serial number that Excel recognizes as a date.
For instance, Timevalue of 08/12/2008 20:00:00 and 08/12/2008 08:00PM yields the same result 0.833333333335759
Datevalue of same date in different format will also yield same result
TIMEVALUE(TEXT(yourdate, "DD/MM/YYYY HH:MM:SS"))
TIMEVALUE(TEXT(yourdate, "DD/MM/YYYY HH:MM AM/PM"))
DATEVALUE(TEXT(yourdate, "DD MMMM YYYY"))
Hey all thanks for your answers. All three of these methods worked.
If TimeValue(Cells(i, 1).Value) = TimeValue(Cells(i, 3).Value) Then
If DateValue(Cells(i, 1).Value) = DateValue(Cells(i, 3).Value) Then
If Abs(CDate(Cells(i, 1).Value) - CDate(Cells(i, 3).Value)) < 0.000001 Then

combo box in a date format

my user form has three separate combo boxes for the users to select the following: Year, Month, Date (they are not dependent). For example if the user selects 2017 (the year), May(the month) and 23(the day) I want vba to enter in column two on my database sheet: "2017/05/23". I want it exactly in this format as a value.
The code below doesn't work. Any help would be appreciated.
With ws
.Cells(lRow, 2).Value = Me.cboYear / Me.cboMonth / Me.cboDay.Value
End With
You're dividing the year by the month, and then dividing that by the day. That's the value your cell is getting.
Build an actual date instead.
.Cells(lRow, 2).Value = DateSerial(cboYear, cboMonth, cboDay)
And then format that date any way you wish, using NumberFormat:
.Cells(lRow, 2).NumberFormat = "yyyy/MM/dd"
DateSerial expects integer values. If your cboMonth contains strings (month names), then you need to work a bit harder for it - the easiest is probably just to use a keyed collection - specify a string key when .Adding the integers to the collection:
Static months As Collection
If months Is Nothing Then
Set months = New Collection
With months
.Add 1, "January"
.Add 2, "February"
.Add 3, "March"
'...
.Add 12, "December"
End With
End If
And then you have an easy lookup:
Dim monthId As Integer
monthId = months(cboMonth)
So your DateSerial would be:
.Cells(lRow, 2).Value = DateSerial(cboYear, monthId, cboDay)

Resources