How to change mm/dd/yyyy to dd/mm/yyyy using VBA - vba

I have a problem in converting mm/dd/yyyy to dd/mm/yyyy date format using VBA.
I have a table like this:
fyi, the table is auto generated from a reporting tool.
Can "string manipulation" or any excel function help? Hope anyone who know how to solve this problem can give me some idea.

Well, from the way you've worded your question I'm not convinced you actually want or need VBA.
Looking at the image you posted it would appear the first cell contains the string 05/06/2013 - 05/10/2013 not the date 05/06/2013. So the first thing you need to do is split out the parts so the built in Excel or VBA functions can convert it.
By Excel Formulas
So we could use SEARCH or FIND to find the "-" and do things dynamically. But I'm feeling lazy so I'll just assume the first 10 characters of the string are the first date and the last 10 characters are the second date. A TRIM function on the source string should make this a bit safer in case of extra spaces before or after.
So if our string 05/06/2013 - 05/10/2013 is in cell A2, we can put =LEFT(TRIM(A2),10) in B2 and =RIGHT(TRIM(A2),10) in C2.
Now these are still strings. Normally I'd use DATEVALUE to convert the strings to dates, but my copy of Excel doesn't like those crazy nonsense* date formats. So we will parse the dates into the DATE function. Putting =DATE(RIGHT(B2,4),LEFT(B2,2),MID(B2,4,2)) and =DATE(RIGHT(C2,4),LEFT(C2,2),MID(C2,4,2)) into cells C2 and D2 respectively.
From here we can recombine them using the TEXT function (much like the format function in VBA) and some string concatenation into your original single-cell date range format. Assuming that's the desired result.
So our final cell, F2, would be =TEXT(D2,"dd/MM/yyyy") & " - " & TEXT(E2,"dd/MM/yyyy"). We could of course combine all those formulas into one big mess like so:
=TEXT(DATE(RIGHT(LEFT(A2,10),4),LEFT(LEFT(A2,10),2),MID(LEFT(A2,10),4,2)),"dd/MM/yyyy") & " - " & TEXT(DATE(RIGHT(RIGHT(TRIM(A2),10),4),LEFT(RIGHT(TRIM(A2),10),2),MID(RIGHT(TRIM(A2),10),4,2)),"dd/MM/yyyy")
By Visual Basic for Applications
It's the same process here, just using VBA functions and syntax instead of Excel formulas.
Now for whatever reason the VBA version of DateValue will accept those dates in my copy of Excel. So I'll use it.
Public Function ChangeDateFormat(inputString As String) As String
Dim firstDate As Date
Dim secondDate As Date
Dim trimmedInput As String
trimmedInput = Trim$(inputString)
firstDate = DateValue(Left$(trimmedInput, 10))
secondDate = DateValue(Right$(trimmedInput, 10))
ChangeDateFormat = Format(firstDate, "dd\/MM\/yyyy") & " - " & Format(secondDate, "dd\/MM\/yyyy")
End Function
Public Sub Test()
Sheet1.[B2] = ChangeDateFormat(Sheet1.[A2])
End Sub
This can be tested either by running the provided Test sub, or ChangeDateFormat can be used as a user defined function in an excel formula =ChangeDateFormat(A2).
Note, in the date formats passed to Format, I escaped the date separator \/ instead of just putting / in. This is because the Format function will automatically replace / with the date separator from your Windows settings. And since I use a modern computer friendly date format, my seperators are dashes...
Footnote
* Life would be so much easier if people would just use ISO 8601. It exists for a reason, a good reason.

Related

VBA: reading date from a string of a specific format

I'm looking for a way to convert strings to Date data type in VBA. I can use CDate() function for this purpose, but it uses its own implicit algorithm for parsing strings and I would like to specify my own format to differentiate between "DD/MM/YY" and "MM/DD/YY", for example.
Please notice that unlike Visual Basic, VBA has no DateTime.TryParseExact function.
ADD: As some answers suggest, I can write my own parser. If there is no built-in solution, it will be my choice.
Do something like this...
strDate = Split(strDate,"/")
newstrDate = strDate(1) & "/" & strDate(0) & "/" & strDate(2)
strDate = CDate(newstrDate)
In this case I would avoid CDate alltogether and instead split the date string into year, month and day and use DateSerial(year, month, day). This way you have full control.
Can you use the below code
Msgbox Format("24/01/2017","MMM, DD, YYYY")
This will give you output as Jan, 24, 2017 . You can use other format which is easily available when you click on the Format cells. Thanks

How to stop " point " to be replaced by a " comma" in the output of a VBA code?

Initially it is important to note that I use MS Excel in Brazilian Portuguese.
That's my code:
Dim C1 As Integer
Dim C2 As Integer
Dim Cod As String
C1 = Worksheets("Dictionary").Range("D1").Value
C2 = Worksheets("Dictionary").Range("D2").Value
Cod = C1 & "." & C2
Worksheets("Dictionary").Range("D3").Value = Cod
Cells:
D1 = 1
D2 = 2
I expected that the output would be "1.2", but it's "1,2"!
What am I doing wrong?
And I apologize for my rusty English
Thank you!
Try this before outputting the value to the range:
Worksheets("Dictionary").Range("D3").NumberFormat = "#"
This changes the format of the cell to Text which prevents Excel to interpret the value you write to it as a number.
You use your Excel in "Brazilian Portuguese". The change may be due to the International Settings in the Windows Control Panel.
If your International Settings define the "," as the decimal separator, then Excel will convert the dot to the comma when you make the assignment in Visual Basic. This behavior makes the VBA code independent of locale settings and so makes the code portable in the international context (I assume that is the intention of this behavior).
If Brazilian Portuguese needs the dot as separator, then set your computer to use the dot as decimal separator, however, it shouldn't matter because when you send the spreadsheet to Brazil, the Excel there will use the correct decimal separator (I assume numbers are stored as binary floating point so dot or comma is only a matter of presentation).
EDIT: strikethrough of text above that would seem a workaround, as setting the international seting/decimal separator makes no difference for the end result.
Sub Replace()
Sheet1.Range("B1").Value = "=SUBSTITUTE(A1,""."","","")"
End Sub
You can change your range accordingly.
Example - Range("B1:B3").Value = "=SUBSTITUTE(A1:A3,""."","","")"

apply user-defined format in excel 2007 vba

The excel 2007 format i am using is: #,##0.00,,,_);[Red](#,##0.00,,,);"-"
if is is possitive, i want the number to display in billions; if negative, in billions and in parentahis; if missing, "-".
It works fine with excel 2007. But when i tried to apply the format in vba, it did not work.
Please use the following numbers as example:
-11467478
224785.66
-5579046
1904770.9
-14916968
The data type i used is variant. shall i use long?
my initial code is something like:
......
with worksheet
'cells(1,1) would be any of the above numbers
.Cells(1, 1).NumberFormat = "#,##0.00,,,_);[Red](#,##0.00,,,);" - ""
end with
.....
I got an erros message run-time error 13, type mismatch
I even tried to decompose the format. but it still did not work.
i am quite new to vba. could anyone help me?
......
This will also work, the dash is one of the characters that don't need to be escaped...
"#,##0.00,,,_);[Red](#,##0.00,,,);-"
You need to use double " for the minus sign. I tested your values and I think it should be:
.NumberFormat = "#,##0.00,,,_);[Red](#,##0.00,,,);""-"""

Working with Excel Dates in vb.net

I am experiencing a problem when attempting to read a date from an excel sheet. (The date column is formatted the same as the short date format of the computer its opened on). I populate the dates from the excel sheet into a datagrid with success, but when I attempt to parse the date (To format it appropriately), I get a error saying the string wasn't a valid DateTime value. The computer's short date format is dd/MM/yyyy. This is the code I use to try parsing the date. The following code is an example of where the process fails.
Dim dateParsed AS DateTime = DateTime.Parse("14/01/2013").ToString("yyyy-MM-dd")
Is there some way to programatically get the system's short date format and use ParseExact instead or any suggestions?
You want to parse exact, using the current cultures short-date format?
Dim dt As DateTime = DateTime.ParseExact(str, "d", CultureInfo.CurrentCulture)
Additionally, if you actually need to see the ShortDate format for yourself get it through the CurrentCulture.
CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
You can try this piece of coding
Dim dt As DateTime = DateTime.Parse("1/14/2013").ToString
Dim f As String = Format(dt, "yyyy-MM-dd")

datediff help in vb.net

Hey all i have 2 dates that i need to see the days that are different.
Problem being is that the server date is not in the normal MM/DD/YYYY format. It is in the format YYYYMMDD.
I've tried the following:
Dim curDate As Date = Format(Now, "yyyyMMdd")
Dim srDate As Date = dr(6)
Dim M As Long = DateDiff(DateInterval.Weekday, curDate, srDate)
The curDate has the error of:
Conversion from string "20110325" to type 'Date' is not valid.
Any help would be great! :o)
David
Try not to hammer a square string peg into a round date hole, that just has way too many ways to break your mallet. The Now function already returns a date:
Dim curDate As Date = Now.Date
Option Strict On at the top of the source code file helps you find these kinds of mistakes.
If you get the string from the server (pray you don't) then use ParseExact() to convert the date:
Dim curDate As Date = Date.ParseExact(serverValue, "yyyyMMdd", Nothing)
Why are you formatting Now like that? You could just do this:
Dim curDate As Date = DateTime.Now.Date
As the other posters have said, you don't need to format DateTime.Now.
But there's something else going wrong here: Format returns a string, and you're trying to assign that to a Date. It's trying to implicitly convert a string, and failing.
In future, when you do have a date-string like "yyyyMMdd" to turn into a DateTime type, use DateTime.Parse
Your problem is the first line; it seems you have Option Strict off in your project (FOR SHAME!), as it would otherwise not compile at all.
Format(Now, "yyyyMMdd") will produce the current date formatted in that manner as a string. The trouble is that you're attempting to assign that output (the string) to a Date variable. Because you have Option Strict off, the compiler indicates this conversion implicitly, and the runtime is attempting to convert your non-standard date string back into a date. This is what's failing.
Changing as little as possible about your code, it should read:
Dim curDate As Date = Now.Date
Dim srDate As Date = DateTime.ParseExact(dr(6).ToString(), "yyyyMMDD", CultureInfo.InvariantCulture).Date
Dim M As Long = DateDiff(DateInterval.Weekday, curDate, srDate)
Step 0: TURN OPTION STRICT ON
There's no reason that new code should be written with this option turned off. There's too much potential for runtime errors that are easily caught at compile time (like this one) with it off. It's a feature that should be banished from the language entirely.
Step 1: Adopt standard .NET types and functions
While this isn't required, it will make your code more readable to other developers and other developers' code more readable to you. Things like Format, DateDiff, Now, etc. are all VB-specific functions that exist primarily to make it easier for classic VB6 applications to be ported over to .NET. Unless there's a particular reason to use the language-specific versions, it's a good idea to use standard .NET functions instead.
Firstly:
"MM/DD/YYYY" is not normal in most of the world, only North America.
China uses "YYYY-MM-DD".
Europe uses "DD/MM/YYYY"
Secondly, if you are parsing a known date format, you can pass a format string to DateTime.Parse. In your case that is what you need to do.
Try
Dim curDate As Date = Now
Dim srDate As Date = mid(dr(6),5,2) & "/" & right(dr(6),2) & "/" & left(dr(6),4)