Change text to specific date format + Excel VBA - excel

I want to change so many dates saved as text in excel sheets to Arabic (Hijri) date format, ie; dd/mm/yyyy to (right to left) yyyy/mm/dd .. it can be done manually be change custom format from Number Format panel ( by choosing the location , calendar type and the right format from list ) then replace the text in cell by same value ..
I need VBA code to automate this replacement process for any ltr date and for existing rtl date just convert the format from general to date ..
another problem , there is some other text around the date in cell like ( dd/mm/yyyy ttt ) . I want the code to remove this text (ttt) ( any text ) and then change to the right format
I found this code but it is not work to my specific need
Changing the date format to yyyy-mm-dd
I appreciate any help , thanks in advance ..

You have a number of separate problems and it is unrealistic to expect someone else to have posted a complete solution to that set of problems or that someone will code a complete solution for you. You need to split your total problem into its components and create or look for a solution to each component.
You have strings that contain CE dates in the format “dd/mm/yyyy”. These dates could be surrounded by text. You give the example “dd/mm/yyyy ttt”. Can ttt contain spaces? Could the “ttt” come before the date? Could the string be as complicated as “aaaa bbbb cccc 12/11/2016 dddd eeee ffff”?
Whatever the situation, I suspect something like:
Dim Part() As String
Part = Split(.Cells(R, C).Value," ")
would be the core of first step. With my complicated example, this would give:
Part(0) = "aaaa"
Part(1) = "bbbb"
Part(2) = "cccc"
Part(3) = "12/11/2016"
: : : :
A loop over the parts of each cell value looking for a string for which IsDate gives True would allow you to find the date so .Cells(R, C).Value = Part(N) would delete the unwanted text.
I would take a copy of your data and try to code a macro that discards the unwanted text. If you can successfully create that macro, you have completed step 1 of your solution. If you have trouble with this macro, you can ask for help here and expect to get it.
The next step is to convert the string “dd/mm/yyyy” to an Excel date. Excel holds dates as the number of dates since 1/1/1900 CE. Replacing:
.Cells(R, C).Value = Part(N)by .Cells(R, C).Value = CDate(Part(N))ought to do the trick. However, Excel sometimes tries to interpret “dd/mm/yyyy” dates as “mm/dd/yyyy”. I think you will be alright but be aware of this possibility.
Your last step is to convert a date from the CE calendar to the Hijri calendar. This is not just a format issue. The two calendars have different year zeroes and different month lengths. There may be a standard conversion function in your country but there does not appear to be one here in the UK. There is help online so you should be able to find a function that will perform the conversion.
You have a number of separate problems and it is unrealistic to expect someone else to have posted a complete solution to that set of problems or that someone will code a complete solution for you. You need to split your total problem into its components and create or look for a solution to each component.
You have strings that contain CE dates in the format “dd/mm/yyyy”. These dates could be surrounded by text. You give the example “dd/mm/yyyy ttt”. Can ttt contain spaces? Could the “ttt” come before the date? Could the string be as complicated as “aaaa bbbb cccc 12/11/2016 dddd eeee ffff”?
Whatever the situation, I suspect something like:
Dim Part() As String
Part = Split(.Cells(R, C).Value," ")
would be the core of first step. With my complicated example, this would give:
Part(0) = "aaaa"
Part(1) = "bbbb"
Part(2) = "cccc"
Part(3) = "12/11/2016"
: : : :
A loop over the parts of each cell value looking for a string for which IsDate gives True would allow you to find the date so .Cells(R, C).Value = Part(N) would delete the unwanted text.
I would take a copy of your data and try to code a macro that discards the unwanted text. If you can successfully create that macro, you have completed step 1 of your solution. If you have trouble with this macro, you can ask for help here and expect to get it.
The next step is to convert the string “dd/mm/yyyy” to an Excel date. Excel holds dates as the number of dates since 1/1/1900 CE. Replacing:
.Cells(R, C).Value = Part(N)by .Cells(R, C).Value = CDate(Part(N))ought to do the trick. However, Excel sometimes tries to interpret “dd/mm/yyyy” dates as “mm/dd/yyyy”. I think you will be alright but be aware of this possibility.
Your last step is to convert a date from the CE calendar to the Hijri calendar. This is not just a format issue. The two calendars have different year zeroes and different month lengths. There may be a standard conversion function in your country but there does not appear to be one here in the UK. There is help online so you should be able to find a function that will perform the conversion.
You have a number of separate problems and it is unrealistic to expect someone else to have posted a complete solution to that set of problems or that someone will code a complete solution for you. You need to split your total problem into its components and create or look for a solution to each component.
You have strings that contain CE dates in the format “dd/mm/yyyy”. These dates could be surrounded by text. You give the example “dd/mm/yyyy ttt”. Can ttt contain spaces? Could the “ttt” come before the date? Could the string be as complicated as “aaaa bbbb cccc 12/11/2016 dddd eeee ffff”?
Whatever the situation, I suspect something like:
Dim Part() As String
Part = Split(.Cells(R, C).Value," ")
would be the core of first step. With my complicated example, this would give:
Part(0) = "aaaa"
Part(1) = "bbbb"
Part(2) = "cccc"
Part(3) = "12/11/2016"
: : : :
A loop over the parts of each cell value looking for a string for which IsDate gives True would allow you to find the date so .Cells(R, C).Value = Part(N) would delete the unwanted text.
I would take a copy of your data and try to code a macro that discards the unwanted text. If you can successfully create that macro, you have completed step 1 of your solution. If you have trouble with this macro, you can ask for help here and expect to get it.
The next step is to convert the string “dd/mm/yyyy” to an Excel date. Excel holds dates as the number of dates since 1/1/1900 CE. Replacing:
.Cells(R, C).Value = Part(N)by .Cells(R, C).Value = CDate(Part(N))ought to do the trick. However, Excel sometimes tries to interpret “dd/mm/yyyy” dates as “mm/dd/yyyy”. I think you will be alright but be aware of this possibility.
Your last step is to convert a date from the CE calendar to the Hijri calendar. This is not just a format issue. The two calendars have different year zeroes and different month lengths. There may be a standard conversion function in your country but there does not appear to be one here in the UK. There is help online so you should be able to find a function that will perform the conversion.

Related

Using Unix US Formatted Date-time-year for calculations in Excel

I have dates that are formatting using the default time formats for Bash (echo $date) for example:
Fri Dec 24 07:35:41 EST 2021
I cannot change this behavior as I don't have permissions to alter our IT solution. I need to be able to load these dates into a UK localised Excel, but any attempts to use the usual Text To Columns DMY approach doesnt work due to the Day, time zone, time etc.
Is the only way to extract the data and re-assemble it or is there a simpler solution?
Try this function . write it to module and call from any cell . Like =makeDateFromStr(A1)
Function makeDateFromStr(ByVal someDate As String) As Date
On Error Resume Next
Dim var As Variant, Mu As Long
var = Split(someDate, " ") ' array to hold all parts of the string-date
Mu = (InStr("JanFebMarAprMayJunJulAugSepOctNovDec", var(1)) + 2) / 3 ' a way to make short string month (Dec) to number
makeDateFromStr = DateSerial(var(5), Mu, var(2)) & " " & TimeValue(var(3)) ' putting all together
On Error GoTo 0
End Function
As far as I can see, if we get rid of the EST and the week day FRI, we can get a valid date value. Note: If you want the weekday, you can use the function WEEKDAY() to get the value 6, which is Friday. (1 is Sunday).
So, to get rid of the weekday, you can use the RIGHT() function.
All weekdays are 3 letters and a space, so we need to get rid of the 4 first characters, like so:
=RIGHT(A1;LEN(A1)-4)
You can put this just underneath your example time, so place this in cell A2.
To remove the EST is a bit more tricky, we need to know where in the text EST is. For this, we use FIND():
=FIND("EST ";A2)
Now we know at which position the text "EST " appears in A2.
Then we can use a simple REPLACE() function, to replace "EST " with nothing. Like so:
=REPLACE(A2;FIND("EST ";A2);4;"")
Note: The 4 refers to the length of "EST ".
This worked for this example, so you can try it out with different data. Just comment below if it isn't working correctly, and with what data and I'll look into it.
Put a date in A1
Put =RIGHT(A1;LEN(A1)-4) in A2
Put =REPLACE(A2;FIND("EST ";A2);4;"") in A3
You could also merge it into 1 cell:
=REPLACE(RIGHT(A1;LEN(A1)-4);FIND("EST ";RIGHT(A1;LEN(A1)-4));4;"")
You could then place this next to the date in A1, so in B1, and drag this formula down for ALL your imported dates. Now it should work for all of your dates.
You could also copy their values and replace the original dates, then remove the formulas, and you will have the same layout and functionality you were expecting from the beginning!

SAS: Date reading issue

I have imported an excel sheet where the date1 is 4/1/16 date2 is 5/29/14 and date3 is 5/2/14. However, when I import the sheet into SAS and do PROC PRINT gives the first 2 variable columns as "42461" and "41788" while the date3 is 05/02/2014.
I need these date formats consistent b/c I am doing a Cox regression with PROC PHREG.
Any thoughts about how to make these dates consistent?
Thanks!
This probably depends on how the data is represented in Excel and how it is imported into SAS. First, are the formats the same in Excel? The first two are being imported as a number. The second as a string.
In Excel, you can format the column using a date format. Perhaps your import method will recognize this. You can also define another column as a string, using the text(<whatever>, "YYYY-MM-DD") to convert to a string in that format.
Alternatively, you can import all as numbers and then add the value to 1899-12-31. That is the base date for Excel. This makes more sense if you think of "1" as being 1900-01-01.
Because your column had mixed numeric (date) and character values SAS imported the field as character. So the actual dates got imported as the text version of the actual number that Excel stores for dates. The ones that look like date strings in SAS are the fields that were strings in Excel also.
Or if in your case one of the three columns was all valid dates then SAS imported it as a number and assigned a date format to it so there is nothing to fix for that column.
The best way to fix it is to make sure that all of the values in the date column are either real dates or empty cells. Then PROC IMPORT will be able to make the right guess at how to import it.
Once you have the strings in SAS and you want to try to fix them then you need to decide which strings look like integers and which should be treated as date strings.
So you might just check if they have any non-digit characters and assume those are the ones that are date strings instead of numbers. For the ones that look like integers just adjust the number to account for the fact that Excel numbers dates from 1900 and SAS numbers them from 1960.
data want ;
set have ;
if missing(exel_string) then date=.;
else if notdigit(trim(excel_string)) then date=input(excel_string,anydtdte32.);
else date=input(excel_string,32.) + '01JAN1900'd -2 ;
format date yymmdd10. ;
run;
You might wonder why the minus 2? It is because Excel starts from 1 instead of 0 and also because Excel thinks 1900 was a leap year. Here are the Excel date numbers for some key dates and a little SAS program to convert them. Try it.
data excel_dates;
input datestr :$10. excel_num :comma32. #1 sas_num :yymmdd10. ;
diff = sas_num - excel_num ;
format _numeric_ comma14. ;
sasdate1 = excel_num - 21916;
sasdate2 = excel_num + '01JAN1900'd -2 ;
format sasdate: yymmdd10.;
cards;
1900-01-01 1
1900-02-28 59
1900-03-01 61
1960-01-01 21,916
2018-01-01 43,101
;

Global VBA date format and decimal separator

Is there a way to change VBA settings globally on PC to accept dates and number on a specified format? (on my case dd/mm/yyyy and comma)
Changing Excel settings doesn't solve it for me.
As an small time VBA developer, I'm mostly creating userforms for data input and validation. Alongside with some basic access privileges, It keeps users (mostly an client's hired arms) from nosing on the database and corrupting it.
But, on form's submitting, the textbox values are saved temporally on spreadsheet's cells. Somehow on this step dates get scrambled and in some cases an 3 decimal places numeric gets multiplied by a thousand (e.g. 1/2/2000 turn to 2/1/2000 and 1,234 turn 1234). It defeats the whole purpose of those applications - data gets corrupted.
I've been able to workaround these using the Format(expression, format) function, but that must be applied every time an date or some precision number is added, or even used on some auxiliary task.
This is an recurrent problem for me because, as an Brazilian, dates are formatted as dd/mm/yyyy and decimal separator is ","(comma) on practically 100% of my local users.
Anybody had similar problems?
TIA
Excel doesn't have a default date format. Excel uses the Window System Date format settings. You can change you system setting by go to Control Panel -> Change date, time and number formats.
Change Date Format in Windows 7, 8.1 and Windows 10 to dd-mm-yyyy
After adjusting the Windows System Settings to dd-mm-yyyy, CDate will expect strings to be in the dd-mm-yyyy.
Range("A1").Value = CDate( "11/01/2016" )
Result: Monday, January 11, 2016
Summary of comments for those to lazy to read.
Alright, as Thomas Inzina pointed, the strait answer to my question is NO, you can't because there isn't such thing in VBA as this Global setting.
As Rory pointed out, the CDate function should solve (indeed it does) this issue, at least as to the date. Again, Thomas answer didn't include it but it points to the windows conf that would be used by the CDate function.
Datetimepicker, suggested by cyboashu, would solve this issue too, but it requires some tweaking on the user's PC to be available. Too much work for me. Although, this approach has the "pretty" advantage, adds value to your project.
Still looking for the comma/dot bad conversion problem. I'll keep editing this answer while none better exists.
Here I write a function called gdate that accepts a string with a date in a specific format. Then I parse the string, then call cdate based on the users date settings.
All I have to do is find/replace cdate with gdate throughout my code. Now I have a way to handle all date formats by always expecting an exact one gdate("mm/dd/yyyy"). Adjust the parsing if you want to expect different format. Building off built-in objects and functions is how we make things work.
Function gdate(ByVal dstring As String)
' 0 = month-day-year; 1 = day-month-year; 2 = year-month-day
d = Mid(dstring, InStr(1, dstring, "/") + 1, Len(dstring) - 5 - InStr(1, dstring, "/"))
m = Left(dstring, InStr(1, dstring, "/") - 1)
y = Right(dstring, 4)
dtype = Application.International(xlDateOrder)
Select Case dtype
Case 0: gdate = CDate(m & "/" & d & "/" & y)
Case 1: gdate = CDate(d & "/" & m & "/" & y)
Case 2: gdate = CDate(y & "/" & m & "/" & d)
End Select
End Function

Date format in vba

I have VBA code which pull the details from .msg file (outlook files) and update in excel sheet. While reflecting the date column, it is showing as "3/9/2016 11:03:27 AM" but I want to show only date and not time.
I used the format option i.e.
Sheet2.Cells(Row + 1, 23) = VBA.Format(sentDate, "dd/MM/yyyy")
but it is showing the date a "8/3/2016 00:00". I want to reflecting only date and nothing else. Please guide me as to what all changes required to reflect only date.
Give this a try:
Sheet2.Cells(Row + 1, 23).Value = sentDate
Sheet2.Cells(Row + 1, 23).NumberFormat = "mm/dd/yyyy;#"
Yet, I have a feeling that the cell does not really contain a date but merely text. So, please also try to change the .NumberFormat to the following first:
Sheet2.Cells(Row + 1, 23).NumberFormat = "General"
If the dates are now showing all as numbers then these are actual dates and the first proposal should work. If not, then these are not dates yet and you'll have to convert the text (which looks like dates) to dates first.
For more information you might want to read this: Difference between date and time w/out work week Excel

VBA dates collected correctly but output wrongly

I grab dates from one spreadsheet and output them onto another spreadsheet. After grabbing the date, when I debug.print it is in the correct format. When I output the date, debug.print also displays the correct format. However, the format on the spreadsheet the value has just been sent to, doesnt show the correct format.
I am using:
Sheets(SheetName).Cells(RowNum, ColNum).Value = Data
Sheets(SheetName).Cells(RowNum, ColNum).NumberFormat = "dd/mm/yyyy"
after I have pasted the value, but the months and days are still switched the wrong way.
Is there something I am doing wrong?? If I right click the cell it thinks it's date is dd/mm/yyyy but instead of 4th Sept it is showing 9th April.
This might be some trouble with localization:
Try using NumberFormatLocal, if DanielCooks tip didn't help ;)
edit: erlier it was statet by mister Cook, to check if the given data is correct.
edit:
With my german version I have quite some trouble to use / as the seperator, that is why i tryied with this code .NumberFormat ="dd-mm-yyyy;#" - works fine; I can switch days and month as I like.
edit:
With .NumberFormatLocal = "TT/MM/JJJJ" I have to use the german shorts for day, month and year, but now I can use / as the seperator.
You should experiment a litte bit with some formats strings ;)
Sorry to resurrect an old post, however I had a problem with VBA outputting a valid date as US style with the actual date changed for example 1st May changed to 5th Jan. I came upon this post but I didn't find the answer I needed here and now that I have worked it out I thought I would share it:
The key is not to define the variable storing the date as a "date" but as a "double", e.g.
Dim ReportDate As Double
ReportDate = Date
Range("E6").Value = ReportDate
This works as it outputs the numeric "date value" which excel then formats locally e.g. 41644 gets formatted as "05/01/14" using UK format or "01/05/14" using US format.
Hope this proves useful to other people (probably me when I forget how I solved it in six months time).
In the end I had to format the cell as "TEXT" to keep the correct format
(1) You need to define the variable to "Date" type to read the input, then set the date format before assigning it to the date variable.
(2) You also need to format the date output to make it work !
'**Read the date input****
Dim date1 as Date
Range("B2").NumberFormatLocal = "dd/mm/yyyy"
date1 = Range("B2").Value
'**Output the date****
Range("E2").Value = date1
Range("E2").NumberFormatLocal = "dd/mm/yyyy"

Resources