Format a date into mm.dd.yyyy format - excel

I have a VBA script in which I am trying to convert the string in "yyyymmdd" format to "mm/dd/yyyy" format. However, when I incorporate format function to achieve this, it's showing
"Run time error-6": Overflow
Can any one help me with this ? The following is the correspondig VBA code.
// NewDate is in the format "yyyymmdd" being extracted out of a file path like "C:\Files\20140611\file.csv"
Required_format=Format(NewDate,"mm/dd/yyyy") // This line shows the error

you will have to format this yourself, because Format doesn't know that it is dealing with a date, it simply sees a string.
Use something like (psuedo code):
y = left(NewDate, 4)
m = mid(NewDate, 5, 2)
d = right(NewDate, 2)
Required_format = m + "/" + d + "/" + y
Just be absolutely sure the format is consitant. Any change (especially the padding is notorious) messes up your format.

Here is one more solution:
CDate(format(NewDate,"mm dd yyyy"))

Here's another method. As you wrote above, NewDate contains an 8 digit string representing a date in yyyymmdd format. The following "one liner" will output a date (as a string) in your desired format:
Format(Format(NewDate, "####/##/##"), "mm/dd/yyyy")

Related

Excel VBA extract date from CSV txt

I'm having trouble extracting this text, exactly as it appears, from a CSV. There are similar questions posted on SO but they don't match my requirements:
I want to extract "31 January 2017" from this row:
4,'31 January 2017','Funds Received/Credits',56,,401.45,
Currently, VBA considers it "31 Jan" without the year. I've tried applying .NumberFormat to the cell (general, text, date).
SOLUTION REQUIREMENTS:
No user action required -- Interact with the file only using VBA (not using File > Import > Wizard)
Compatible with VBA Excel 2003
Extract the full text regardless of Excel or operating system date settings
Thank you for your ideas
You can use the split function, using the comma as a delimiter like this:
sResult = Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1)
If you dont want the single quotes, then add the replace function like this:
sResult = Replace(Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1), "'", "")
If you include the "Microsoft VBScript Regular Expressions 5.5" Reference, you can set up a pattern that will extract the whole date if it is found. For example:
Dim tstring As String
Dim myregexp As RegExp
Dim StrMatch As Object
tstring = 'Line from the CSV, or entire CSV as one string
Set myregexp = New RegExp
myregexp.Pattern = "\d{1,2} [A-Z]{3,9} \d{4}"
Set StrMatch = myregexp.Execute(tstring)
You get the benefit from this method that all the dates in the CSV will be pulled out at once, much faster than using a split line by line. Additionally, the dates may be accessed by using
DateStr = StrMatch.Item(index)
for the whole string line, or substrings can be set up to get specific parts of the string(Such as month, day, year).
myregexp.Pattern = "\(d{1,2}) ([A-Z]{3,9}) (\d{4})"
Set StrMatch = myregexp.Execute(tstring)
DateStr = StrMatch.Item(index1).SubMatches(index2)
It is a very powerful tool, with a simple set of symbols for development of patterns. I highly suggest you familiarize yourself with it for manipulation of large strings.

Now() is giving an error

I am getting an error in the below code.
Dim CurrentTime As Date
CurrentTime = Format(Now(), "hh:mm AM/PM")
If CurrentTime = ActiveSheet.Range("I1") Then
Call SendEMail
End If
When the time is right, then the macro is debugging and Now is highlighted.
Could anyone solve this problem?
You are not getting an actual error are you? It is just not working as expected.
Matt Cremeens has identified your issue I believe, you have declared CurrentTime as a date data type. A date data type stores a number representing a time/date, however you are asking for it to store string information (AM/PM) too which is can't so it is getting stripped out.
The results is cell one may hold a value like '10:30 AM' but the Format(Now(), "hh:mm AM/PM") code going into the Date variable is resulting in '10:30:00', so the two are never matching as strings. Copy as Matt has suggested and this should work (Dim CurrentTime As String).
Better yet, use the date comparison function DateDiff:-
If DateDiff("s",ActiveSheet.Range("I1"),Time()) > 0 then
SendEmail
End If
This is saying if the time now is greater than the value in I1 (to the second) then run SendEmail.
I don't have the environment to test the solution right now but from what I remember you don't need the brackets in 2007 and also you don't need the format.
Try the following code and see if that fits your need:
If Hour(Now) = ActiveSheet.Range("I1") Then
(...)
End If

Convert String to Excel Date and Time, with specific string format

I've got an Excel/VBA macro which list files in a directory.
Filenames are in format : yyyy-MM-dd#hh-mm-ss_[description].csv
for instance : 2013-07-03#22-43-19_my-file.csv
I then need to get the first part of the filename into an Excel Date object (including a Timestamp)
I found the CDate() function, but it doesn't take any "format" parameter, and the Format() function works the wrong way, ie to convert a String to a Date.
I'd like to get a function with takes a String and a format, and returns an Excel Date/Time object.
Is there a function designed to do that ?
Thanks,
Try this out:
Function ParseDateTime(dt As String) As Date
ParseDateTime = DateValue(Left(dt, 10)) + TimeValue(Replace(Mid(dt, 12, 8), "-", ":"))
End Function

Excel : Date format issue

I have few cells where I fill date in those using 'FormatDatetime' function,
code:
Range("AX1") = FormatDateTime((Docx.getAttribute("r1ed")))
Range("AX2") = FormatDateTime((Docx.getAttribute("r2ed")))
Range("AX3") = FormatDateTime((Docx.getAttribute("r3ed")))
Range("AX4") = FormatDateTime((Docx.getAttribute("r4ed")))
If date is separated by "." all the cells would show like "12.1.2013",but if I change my system date format separated by "-","AX4" shows date as still "12.1.2013".but other shows correctly.
I need to have fix for this,since I use these dates' for calculation later in VBA.
Please suggest some answers.
I think your problem is that FormatDateTime() returns a string, change it to DateValue() instead. If the return from Docx.getAttribute() contains dots you'll need to replace them with slashes first.
So;
'[AX1] is the same as Range("AX1")
[AX1] = DateValue(Docx.getAttribute("r1ed"))
[AX2] = DateValue(Docx.getAttribute("r2ed"))
[AX3] = DateValue(Docx.getAttribute("r3ed"))
[AX4] = DateValue(Docx.getAttribute("r4ed"))
Or, if there are dots;
[AX1] = DateValue(Replace(Docx.getAttribute("r1ed"), ".", "/"))
[AX2] = DateValue(Replace(Docx.getAttribute("r2ed"), ".", "/"))
[AX3] = DateValue(Replace(Docx.getAttribute("r3ed"), ".", "/"))
[AX4] = DateValue(Replace(Docx.getAttribute("r4ed"), ".", "/"))
If this doesn't solve the issue, can you please post more info about what Docx.getAttribute() is returning please.
Edit: Also, knowing the format you need the cells to contain would be helpful - I'm assuming proper dates will be acceptable - You might need a string with a date in a certain format. If that's the case you could wrap the above with something like;
[AX1] = Format(DateValue(Docx.getAttribute("r1ed")), "dd/mm/yyyy")
It might be that FormatDateTime() is betraying you, Format() might be more flexible

Format a cell as arbitrary currency regardless of locale, using VBA

This is really bugging me as it seems pretty illogical the way it's working.
I have a macro to format a cell as a currency using a bit of code to obtain the currency symbol.
Here is the code involved:
Dim sym As String
sym = reportConstants(ISOcode)
'Just use the ISO code if there isn't a symbol available
If sym = "" Then
sym = ISOcode
End If
With range(.Offset(0, 3), .Offset(3, 3))
.NumberFormat = sym & "#,##0;(" & sym & "#,##0)"
Debug.Print sym & "#,##0;(" & sym & "#,##0)"
End With
reportConstants is a dictionary object with currency symbols defined as strings. E.g. reportConstants("USD") = "$". This is defined earlier in the macro.
When the macro runs it gets the ISO code and should then format the cell with the corresponding currency symbol.
When I run it in one instance the ISO code is "USD" - so sym is defined as "$" - but it still formats the cell with a pound sign (£). When I debug.print the format cell string it shows $#,##0;($#,##0) so, as long as I got my syntax correct, it should use a dollar sign in the cell. But it uses a £ sign instead. (I am running a UK version of excel so it may be defaulting to £-sign, but why?)
Any help greatly appreciated.
I just recorded a macro to set the format to $xx.xx and it created this: [$$-409]#,##0.00. Looks like the -409 localises the currency to a particular country; it works without it - try changing yours to .NumberFormat = "[$" & sym & "]#,##0.00"
Btw guess I read your question somewhat after posting ;) Excel is well influenced by the regional settings of your computer for currency, language, dates... Using numberformat can force it to keep the sign you require. if it is a matter of rounding up you can try to: On Excel 2010, go to File - Options - Advanced and scroll down to "When calculating this workbook" and click on the "set precision as displayed" and OK out. 
Try this: given your values are numerics/ integers/decimals....
Range("a2").Style = "Currency"
Or you can use format:
Format(value, "Currency")
Format(Range(a2).value, "Currency")
References:
http://www.mrexcel.com/forum/excel-questions/439331-displaying-currency-based-regional-settings.html
http://www.addictivetips.com/microsoft-office/excel-2010-currency-values/
(PS: I am on mobile, you may try these two links)

Resources