Problem with CDate function in VBA - excel

I'm using CDate to convert a particular date formatted as string to the Excel Date type. I wrote a small UDF for this conversion; however when I run the function as a in-cell function, it returns a number and the calling cells default format is set to Number type. When I manually convert it to Date type, Excel will display the correct date entry.
So, I need to know whether there is a way to set the default format of the calling cell to Date type through my Date conversion macro. Otherwise, the user has to manually change the format of each of cell.
e.g
Function Test()
Test = CDate("2010/12/23")
End Function

The calling cell is exposed via Application.ThisCell however your going to have to manually format before/after the call as an Excel UDF cannot modify the physical characteristic of a cell.

Perhaps you can run something after the cells have been entered?
Dim c As range
For Each c In ActiveSheet.UsedRange.Cells
''Case sensitive
If c.Formula = "=test()" Then
c.NumberFormat = "d/mm/yyy"
End If
Next

It sounds like what you want to do is actually a two-part process: convert a value in a cell (or range of cells) to a date and then display it as a date, as opposed to simply converting a text value that looks like a date to a date value.
If that is the case, then I would recommend modifying Remou's suggestion like so (using UsedRange can be problematic on worksheets containing large amounts of data):
Dim c As Range
For Each c In Selection.Cells
c.Value = CDate(c.Value)
c.NumberFormat = "m/d/yyyy"
Next c
The user would then need to select the cells to which the formatting should be applied and run the macro; it sounds as though you do not wish this to happen, but I'm not sure that is possible.
Depending on how you want to use the macro, you can add additional checks: for example, you could apply the formatting only to non-blank cells currently formatted as text (c.Value <> "" and c.NumberFormat = "#").

If you return the data as a string and in a format that Excel automatically converts to a date, you can get the cell to format properly.
Function Test() As String
Test = Format(DateValue("2010/12/23"), "mm/dd/yyyy")
End Function
This works in US Excel, but if you need it to be language agnostic, I think you'll have problems.

Related

SumIfs VBA function not working properly in macro

I have a form that is supposed to show the total sum of different numeric values between two dates, a start date and a finish date. For this, I thought the best option would be to use the SumIfs WorkSheetFunction. However, after trying to code this, the function is not working properly. I am not sure of what is wrong. If I type the exact same formula on the worksheet that has the table with my sample data, it works perfectly.
So, the form I designed is the following:
A second label and textbox will be added for the finish (or end) date. However, I thought it would be better to do that once I get the code to work with a single date in the beginning. The textbox where the user will insert the start date is called tbxDate and the textbox that will show the resulting sum is called tbxBalance. The button that triggers the SumIfs functions is called cmdCalculate.
Also, the table that stores the data (which only has one row of data so far for testing purposes) is this one:
The table name is Sales, and the worksheet name is SalesWS. I thought the code should be pretty simple, unless there is something I am missing. What I did was:
Private Sub cmdCalculate_Click()
Set SalesRange = Worksheets("SalesWS").Range("Sales[TOTAL]")
Set DatesRange = Worksheets("SalesWS").Range("Sales[DATE]")
tbxBalance = Application.WorksheetFunction.SumIfs(SalesRange , DatesRange , ">=" & tbxDate)
End Sub
The issue is that the >= part of the criteria is failing. I only get proper results using only the greater than or less than conditions. For example, if I enter the date 09/08/2020 in the textbox the result in the balance textbox is 0, but if I enter the date 08/08/2020 or anything before it works. It just ignores the condition to sum the values if the date is equal to what is entered. It only works with dates greater or less than what the user inputs in the textbox, excluding the chosen date.
I already checked that the column with the dates in the table is formatted properly.
The version of your code given below should work provided your DATE range contains true dates and tbxDate contains a string VBA can recognise as a date.
Private Sub cmdCalculate_Click()
Dim Fun As Double
Set SalesRange = Worksheets("SalesWS").Range("Sales[TOTAL]")
Set DatesRange = Worksheets("SalesWS").Range("Sales[DATE]")
Fun = Application.WorksheetFunction.SumIfs(SalesRange, DatesRange, ">=" & CLng(CDate(tbxDate.Value)))
tbxBalance = Format(Fun, "#,##0.00")
End Sub
Remember that tbxBalance will cotnain a text string, not a number. Use Excel's NUMBERVALUE function to convert the formatted number you have in tbxBalance after the above code back to a number you can calculate with.

After copy and paste values from one workbook to another, a formula doesn't work with a specific range until I doubleClick cells

Using VBA I open one workbook, copy data and paste it to another workbook. In the second workbook I set a formula for specific range of custom format of values(dd/mm/yyyy hh:mm) but the formula doesn't work. Values are kept on the left side of cells as a text with custom format until I double click. Format in both workbooks(worksheets) is the same and I want to keep it.
I've been trying fix it using:
range.TextToColumns Destination:=range DataType:=xlFixedWidth FieldInfo:=Array(Array(0,9),Array(1,1), Array(16,9))
It works within halfway. Date is fit to the right side of cells but my day from custom date is 17 days less???:D When I omit Array(0,9) it returns additional date 02/01/1990 and my original date is moved to the next column.
Has anyone got any solution?
How exactly does .TextToColumns work? How Can I correctly declare arg for FieldInfo to receive original date and fit it to the right side of cells?
below is an example of how to convert a date that is in text format (cell B1) to an actual date. Notice how a text format is left aligned and a date format is right aligned.
Keep in mind that a date is a number-> the integer part is the date and the decimal part is the time.
Public Sub sTestDate()
Dim v As Variant
v = Sheet1.Range("B1").Value
Sheet1.Range("B2").Value = CDbl(CDate(v))
Sheet1.Range("B3").Value = CDbl(CDate(v))
Sheet1.Range("B3").NumberFormat = "dd/mm/yyyy hh:mm"
End Sub

Copying date Word to Excel - wrong format

I have been trying to solve an issue I have with copying dates from Word document to Excel using VBA.
My issue is the format. If I put dd/MM/yyyy it will change during the process to MM/dd/yyyy and I cannot solve the issue.
Basically for copying I am using this line:
Sheets("wImp").Range("AA" & i) = wdDoc.ContentControls(1).Range.Text
However during the process the data is modified.
I originally used LegacyForms but it did work and I hoped Date Picker would help but it does not. And in a case the date is impossible to switch like 21/12/2017 it will stay as it should. But when it can be switched like 1/5/2017 it will be switched to 5/1/2017.
!!! Nevertheless the cell format stays dd/MM/yyyy for all the dates, but the months and days position is switched.
See below for what I have as input in Word and the output in Excel.
Word:
Excel:
If you want to use the continental date format "dd/mm/yyyy" in your sheet you must use Format() function. So, try this:
Sheets("wImp").Range("AA" & i) = Format(wdDoc.ContentControls(1).Range.Text, "dd/mm/yyyy")
Sheets("wImp").Range("AA" & i).NumberFormat = "dd/mm/yyyy"
Oficial documentation of Format() function
Sub test()
ActiveSheet.Range("A1").NumberFormat = "#"
ActiveSheet.Range("A1").Value = "01/05/2017"
ActiveSheet.Range("A2").NumberFormat = "m/d/yyyy"
ActiveSheet.Range("A2").Value = "01/05/2017"
ActiveSheet.Range("A3").NumberFormat = "yyyy/m/d;#"
ActiveSheet.Range("A3").Value = "01/05/2017"
End Sub
Try something like this.
Excel will convert the data during copy.
So, change "NumberFormat" before copy.
Assigning a string to the cell makes Excel think that the string should be interpreted in a "mm/dd/yyyy" format irrespective of your locale (and irrespective of the cell's date format).
So convert the string to a Date using the CDate function (which will be done using your system date/time settings) before assigning the value to the cell.
Sheets("wImp").Range("AA" & i) = CDate(wdDoc.ContentControls(1).Range.Text)
That date can then be displayed in whatever date format you want to use for the cell.

IF statement in Excel that looks at the value of a cell being a date

How would I create an if statement within a cell that looks at another cell's value and copies the value to it if it is a date. If it's not a date it leaves the cell blank.
So far I have come up with something like this but it is obviously not working:
=if('TRACKING FILE'!I10=DATE,'TRACKING FILE'!I10, "")
Something like:
=IF(NOT(ISERROR(DATEVALUE(TEXT(A1,"mm/dd/yyyy")))),TEXT(A1,"mm/dd/yyyy"),"")
This copies numeric representation of dates or typical dates. Change the "true" according to your needs, depending on what you are going to do with it.
=IF(NOT(ISERROR(DATEVALUE(TEXT(F9,"mm/dd/yyyy")))),F9,"")
=IF(NOT(ISERROR(DATEVALUE(TEXT(F9,"mm/dd/yyyy")))),DATEVALUE(TEXT(F9,"mm/dd/yyyy")),"")
There is no direct isdate function in Excel, but you can create your own function in VBA and apply it in your worksheet.
Function checkDate(oRange As Range) as boolean
checkDate = isdate(oRange)
End Function
In your worksheet:
=IF(checkDate(C8) = TRUE;C8;"")
You need to set the format yourself, as Excel displays it standard as a number.

Excel Date to String conversion

In a cell in Excel sheet I have a Date value like:
01/01/2010 14:30:00
I want to convert that Date to Text and also want the Text to look exactly like Date. So a Date value of 01/01/2010 14:30:00 should look like 01/01/2010 14:30:00 but internally it should be Text.
How can I do that in Excel?
=TEXT(A1,"DD/MM/YYYY hh:mm:ss")
(24 hour time)
=TEXT(A1,"DD/MM/YYYY hh:mm:ss AM/PM")
(standard time)
Here is a VBA approach:
Sub change()
toText Sheets(1).Range("A1:F20")
End Sub
Sub toText(target As Range)
Dim cell As Range
For Each cell In target
cell.Value = cell.Text
cell.NumberFormat = "#"
Next cell
End Sub
If you are looking for a solution without programming, the Question should be moved to SuperUser.
Here's another option. Use Excel's built in 'Text to Columns' wizard. It's found under the Data tab in Excel 2007.
If you have one column selected, the defaults for file type and delimiters should work, then it prompts you to change the data format of the column. Choosing text forces it to text format, to make sure that it's not stored as a date.
In some contexts using a ' character beforehand will work, but if you save to CSV and load again this is impossible.
'01/01/2010 14:30:00
Couldnt get the TEXT() formula to work
Easiest solution was to copy paste into Notepad and back into Excel with the column set to Text before pasting back
Or you can do the same with a formula like this
=DAY(A2)&"/"&MONTH(A2)&"/"&YEAR(A2)& " "&HOUR(B2)&":"&MINUTE(B2)&":"&SECOND(B2)
I have no idea about the year of publication of the question; it might be old now. So, I expect my answer to be more of a reference for future similar questions after my post.
I don't know if anybody out there has already given an answer similar to the one I am about to give, which might result -I think- being the simplest, most direct and most effective: If someone has already given it, I apologize, but I haven't seen it. Here, my answer using CStr instead of TEXT:
Asuming cell A1 contains a date, and using VBA code:
Dim strDate As String
'Convert to string the value contained in A1 (a date)
strDate = CStr([A1].Value)
You can, thereafter, manipulate it as any ordinary string using string functions (MID, LEFT, RIGHT, LEN, CONCATENATE (&), etc.)
If you are not using programming then do the following
(1) select the column
(2) right click and select Format Cells
(3) Select "Custom"
(4) Just Under "Type:" type dd/mm/yyyy hh:mm:ss
In Excel 2010, marg's answer only worked for some of the data I had in my spreadsheet (it was imported). The following solution worked on all data.
Sub change()
toText Selection
End Sub
Sub toText(target As range)
Dim cell As range
Dim txt As String
For Each cell In target
txt = cell.text
cell.NumberFormat = "#"
cell.Value2 = txt
Next cell
End Sub
As Text is localized it will break when trying you try to share your files over diffrent cultures. ÅÅÅÅ-MM-DD might work perfectly in sweden, is US, Germany or israel it will turn to shit.
The reasonable solution would be that english was accepted everywhere, but it's not.
Basically DON'T EVER use text as intended to format dates.
Here is how to create the date in ISO format. TEXT is used to ensure leading
=YEAR(A1)&"-"&TEXT(MONTH(A1);"00")&"-"&TEXT(DAY(A1);"00")
If you want it backwards, sideways or whatever, just change it.
https://www.reddit.com/r/ISO8601/comments/enhlp6/logic_of_the_different_date_time_systems_with/
The selected answer did not work for me as Excel was still not converting the text to date. Here is my solution.
Say that in the first column, A, you have data of the type 2016/03/25 21:20:00 but is stored as text. Then in column B write =DATEVALUE(A1) and in column C write =TIMEVALUE(A1).
Then in column D do =B1+C1 to add the numerical formats of the date and time.
Finally, copy the values from D into column E by right clicking in column E and select Paste Special -> Paste as Values.
Highlight the numerical values in column E and change the data type to date - I prefer using a custom date of the form YYYY-MM-DD HH:MM:SS.

Resources