Change date format so that DAYS() formula work - excel

I'm trying with VBA to convert a date format in a table column so that I can use it in formulas.
The column contains dates with format "general", not "date" and looks like this: 13/04/2019. So it needs to be dd/mm/yyyy and recognized as a date.
I've looked up online and struggle to find something that works.
I've tried:
.numberformat = "dd/mm/yyyy"
but it didn't work
This is the code I'm trying.
With wsDormant.ListObjects("Table_Dormant_Stock").ListColumns.Add
.DataBodyRange.Formula = "=DATE(RIGHT([#[Days Last Sold]],4), MID([#[Days Last Sold]],3,2), LEFT([#[Days Last Sold]],2))"
End With
'Change date to amount of days
With wsDormant.ListObjects("Table_Dormant_Stock").ListColumns.Add
.DataBodyRange.Formula = "=DAYS($C$8,[Days Last Sold])"
wsDormant.ListObjects("Table_Dormant_Stock").ListColumns("Days Last Sold").DataBodyRange.Value = .DataBodyRange.Value
.Delete
End With
I'm getting #value when I try the formula.
It needs to convert the cell format to date. The formulas that uses dates don't seem to like the date format in dd/mm/yyyy. But are happy with yyyy/mm/dd.

You should first convert your "pseudo-dates" into "real" dates. Select the cells and run:
Sub FixDate()
Dim d As Date, r As Range, v As String
For Each r In Selection
v = r.Text
r.Clear
arr = Split(v, "/")
d = DateSerial(arr(2), arr(1), arr(0))
r.Value = d
r.NumberFormat = "dd/mm/yyyy"
Next r
End Sub

Related

Is there a way to convert a Long Date to short date in Excel?

I have an exported file that gives me a list of long dates in format General.
ex: Friday, August 28, 2020
I am trying to convert them into short dates. I've tried using CDate function, but I get a mismatch error. I find this odd because the cell has the exact long date form.
I've tried running a ton of code. Here's the most recent one I tried. It changs the cell format into Long Date. then uses Cdate and gets a mismatch error.
Sub formatdate()
'
' Macro1 Macro
'
Range("J2").Select
Selection.NumberFormat = "[$-F800]dddd, mmmm dd, yyyy"
MsgBox (CDate(Range("J2")))
End Sub
Any help would be much appreciated!
As #scottcraner says:
Dim v
With Range("J2")
v = .Value
v = Mid(v, InStr(v, ",") + 1, 100)
.Value = DateValue(v)
End With

Convert date to Date Function

I want to convert a date in a cell to the date function so it is a formula. How do I get the date (using VBA), any date, say, 13 Jun 2020 to =DATE(2020, 6, 13) using variables for the year, month, and day. My code I have tried but won't work. The activecell shows 13-Jun-2020 as a date but appears in the function box as 13/06/2020
Sub ConvertDateToDateFunction()
Dim mvDay, mvMth, mvYr As Integer
mvDay = Left(ActiveCell, 2)
mvMth = Mid(ActiveCell, 4, 2)
mvYr = Right(ActiveCell, 4)
ActiveCell.Value = "=DATE(mvYr, mvMth, mvDay)"
End Sub
You have two problems. Here is the solution to the smaller one. The code below would do what you intend. It would convert a text string in the ActiveCell to a function of similar value and insert it in the cell below the ActiveCell.
Sub ConvertDateToDateFunction()
' if you don't say what it's supposed to be it'll be a Variant
Dim mvDay As String, mvMth As String, mvYr As String
mvDay = Left(ActiveCell.Value, 2)
mvMth = Mid(ActiveCell.Value, 4, 2)
mvYr = Right(ActiveCell.Value, 4)
ActiveCell.Offset(1).Formula = "=DATE(" & mvYr & "," & mvMth & "," & mvDay & ")"
End Sub
It's not entirely easy to insert a date as a text string in Excel because Excel will try to recognize a date for a date. Observe that any part of a string is a string, not an integer.
Now about your much bigger problem which is that you don't understand how Excel handles dates. It is such a big problem because you are trying to create a date in Excel in various ways and you run into all sorts of trouble. Read up on the subject here.
To give you a taste of what you will learn: what you see displayed in a cell isn't what the cell contains. There might be a formula in it and you see a number. And there might be a date and you see a string. What you see is determined by the cell's format. I think Chip Pearson's article will cover that topic. If you need to know more, look for "Cell formatting" on the web.
Your macro won't work because the date is a "real date" and not a string.
Try the following to convert the contents of cells containing a real date to a formula which will return the same date:
Option Explicit
Sub dtToFormula()
Dim R As Range, C As Range
Dim vDateParts(2)
Set R = [a1:a10]
'Set R = ActiveCell 'or Selection whatever range you want to convert
For Each C In R
If IsDate(C) And Not C.HasFormula Then
vDateParts(0) = Year(C.Value2)
vDateParts(1) = Month(C.Value2)
vDateParts(2) = Day(C.Value2)
C.Formula = "=DATE(" & Join(vDateParts, ",") & ")"
End If
Next C
End Sub

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.

I have a date and time value in a cell and i want to make the seconds as 00, how do i do it?

I have a cell value, for example
A1 = 17/06/2016 19:00:46
i want to change it to 17/06/2016 19:00:00
so basically the seconds have to be 0 but i can not seem to be able to achieve that with the formatting. I did the format as dd/mm/yyyy hh:mm, but the seconds is still retaining.
i will be using these values to match the values in a different sheet using Application.Match in vba. the different sheet has the seconds as 0, hence, to match it i need to be convert these to 0 seconds.
Thank you.
The easier way to achieve this:
Function DateWithZeroSeconds(MyDate As Date)
DateWithZeroSeconds = Format(MyDate, "dd/mm/yyyy h:m") & ":00"
End Function
Select the cells you wish to convert and run this short macro:
Sub SecondKiller()
Dim d As Date, d2 As Date
For Each r In Selection
d = r.Value
r.Value = DateSerial(Year(d), Month(d), Day(d)) + TimeSerial(Hour(d), Minute(d), 0)
Next r
End Sub
An other way, format the Excel cell, and then show the seconds as 00's:
Sub FormatRange_AsDate(ByVal Rg As Range)
With Rg
.NumberFormat = "d/m/yyyy h:mm:ss;#" 'give the format to the cell , showing seconds
.Value = Format(.Value, "d/m/yyyy h:m") & ":00" 'changing the seconds to "00", don't use .value2
End With
End Sub

VBA Convert and combine date and time

I am new to VBA and am working an a macro that will help me transform call records into something useful for analysis.
Column E contains the Date of Call which is formatted YYYYMMDD. I need to convert to MM/DD/YYYY. (i.e. 20140101 convert to 1/1/2014)
Column F contains the Time of Call which is formatted HHMMSS or HMMSS depending on whether the hour has two digits or one. I need to convert to HH:MM:SS (i.e. 130101 or 90101 which needs to convert to 13:01:01 and 9:01:01, respectively). Because the hour is missing the tens digit if the value is below ten, (below) I have added a "0" to the beginning of the value so I can use the date function.
I currently enter the the following formula in Column K and autofill until the end of the range:
=DATE(LEFT(E2,4),MID(E2,5,2),RIGHT(E2,2))+TIME(LEFT(IF(LEN(F2)=5, 0&F2, F2),2),MID(IF(LEN(F2)=5, 0&F2, F2),3,2),RIGHT(IF(LEN(F2)=5, 0&F2, F2),2))
The formula results in a value like "1/1/2013 13:01:01".
Can someone help me write the VBA code to automate this process?
Thank you.
Created separate UDFs for this. Paste the following into a module.
Function MorphDate(DateRng As Range)
Dim DateStr As String: DateStr = DateRng.Value
Dim Yr As String, Mt As String, Dy As String
Yr = Left(DateStr, 4)
Mt = Mid(DateStr, 5, 2)
Dy = Right(DateStr, 2)
MorphDate = Format(DateSerial(Yr, Mt, Dy), "m/dd/yyyy")
End Function
Function MorphTime(TimeRng As Range)
Dim TimeStr As String: TimeStr = TimeRng.Value
Dim Hh As String, Mm As String, Ss As String
If Len(TimeStr) = 5 Then TimeStr = "0" & TimeStr
Hh = Left(TimeStr, 2)
Mm = Mid(TimeStr, 3, 2)
Ss = Right(TimeStr, 2)
MorphTime = Format(TimeSerial(Hh, Mm, Ss), "hh:mm:ss")
End Function
Function MorphDateTime(DateRng As Range, TimeRng As Range)
Application.Volatile
MorphDateTime = CDate(MorphDate(DateRng)) + CDate(MorphTime(TimeRng))
End Function
Now you can use the formulas MorphDate to change the date, MorphTime to change the time, and MorphDateTime for a combination of both.
Screenshot:
Let us know if this helps.
EDIT:
If you want to use it inside a subroutine, add the following code to the module:
Sub MorphingTime()
Dim DateRng As Range, Cell As Range
Set DateRng = Range("E2:E100") '--Modify as needed.
For Each Cell in DateRng
Range("K" & Cell.Row).Value = MorphDateTime(Cell, Cell.Offset(0,1))
Next Cell
End Sub
Hope this helps.

Resources