Date value changes when copied - excel

I have cells containing a simple concatenation function with D24 as the previous year (e.g. 15) and a custom format (MMM JJ)
CONCATENATE("Apr ",$D$24)
When I am copying and pasting these cells with a VBA then "Apr 15" becomes "15.04.16" and because of the formatting "Apr 16"
Selection.Value = Selection.Value
Was is the reason behind this? Is there another solution than just changing the format to text?

Excel will generally try to convert anything that looks like a date into a real date (serial number where 1 = 1 Jan 1900). One way to avoid that, and remove the formula as you are doing above, would be to pre-format as text. So:
With Selection
.NumberFormat = "#"
.Value = .Text
End With
might do what you want.
There are other ways, but if you don't change the cell format to text, or prefix the entry with a single quote ', any subsequent editing of that cell, even inadvertent selection, raises the risk of converting it to the real date.

That depends on what you want in your cell. Dou you want a string or a date?
If you want a string:
either format as text or
add a ': CONCATENATE("'Apr ",$D$24)
if you want a date:
use the following formula instead of concatenate: =DATE($D$24,4,1)

If you simply Copy Paste it, only the Value is pasted not the formatting (if I remember right)
Try to avoid using Selection instead use Range.
And use Range.Copy and Range.PasteSpecial Paste:=xlPasteFormats so your formatting is pasted with the values.

Related

How to use VBA to apply Auto Filter per month/year and add a value in another range based on the month/ Year filter

How can I use VBA to apply a filter in a column (per month/Yer) so the range corresponding to that date will receive value as Month-Yes in another column?
Or in this case, would be better to use if the value in the column named CreationDate is = Jan/2020 then range on column Month_Yr will be 01_2020.
Basic the VBA need to check dates on column A and if it writes only the month and year on column B.
Should I use the auto filter or Vlook?
Any ideas how can I get the result I need?
Following your comments, you can use
With Sheet1.Range("B2:B" & last_row)
.Formula = "=TEXT(A2,""m\_yyyy"")"
' I suggest you then delete the formulae
.Value = .Value
End with
Note the way to add double quotes inside a string is to use 2 of them (i.e. escape it with another double quote), therefore the string "=TEXT(A2,""m\_yyyy"")" will result in the formula =TEXT(A2,"m\_yyyy").
Also note the underscore character has a special meaning in excel number formatting and therefore, if you want it displayed in the final string then you need to escape it with a backslash. (I know it looked like a typo in my comment above, but it is important)

excel vba change format of date - numbers

Excel changes the following values automatically to a number, I guess because he considers them as a date:
2/2/1 becomes 36527
4/2/1 becomes 36926
I have a column with a combination of different formats now:
2/1/
3/1/
8/7/
36527
1/0/0
36926
Which VBA code can I use to convert the numbers back to their original format? The other values should stay the same.
I know the cDate function, but I guess it's not useful here?
I have already this in my VBA code for pasting values
ActiveWorkbook.Sheets("Import").Columns("A:AH").NumberFormat = "#"
ActiveWorkbook.Sheets("Import").Range("A1").Select
ActiveSheet.Paste
You can't change them back. Once Excel converts them, the original value is gone. Before you input the value, you can prepend an apostrophe to force it to text.
ActiveCell.Value = "'" & sMyValue
or as #Scott Craner commented, you can format the cell as text
ActiveCell.NumberFormat = "#"
ActiveCell.Value = sMyValue

Obtain custom cell format notation as text

I have a column containing quantities. Along with these quantities there is a unit of measure displayed, such as KG, or L. However this isn't hard copied text but rather some custom formatting rule, for example #.##0 "L". What I would like is to extract these UOMs into their own seperate column as text. Is there some way I can access these formatting rules to do this or is there some other method that will get me what I want?
My solution for completeness.
Function getcellformat(ByRef valuecell As Range) As String
getcellformat = Replace(Split(valuecell.NumberFormat, " ")(1), Chr(34), "")
End Function
Thanks to teylyn for pointing out the .NumberFormat
You can use the .NumberFormat property to show the number format applied to a specific cell
Here's a screenshot from the Immediate Window for the Number Format of cell A1 of the current sheet

Excel formulas are not working - not recognizing numbers

I've pasted some numbers on Excel spreadsheet and wanted to do some calculations with it. The problem is that Excel isn't recognizing the numbers. I've already tried several methods to convert them into numbers and none of them works: paste/special multiplying by 1; formating each cell to the number/scientific number format. And there isn't also an error message on the top right corner of each cell like I've read on the internet indicating that there is a number written as text. If I retype each number, Excel recognizes it.
To make sure that the problem was really that the numbers were understood by Excel as text, I tried the functions ISNUMBER(), that returned FALSE and ISTEXT() that returned true.
I want to know how I can fix that problem without having to type into each cell.
Ps. the numbers are in scientific number format, i.e., 1,085859E+001 
Since the column is text the cells are formatted as text.
you use Value to convert the text into a number so the formula will work
A2 = 123
A3 = 123 Richard
Formula
=isnumber(A2) result is false
use
=isnumber(value(A2)) result is True
I was having the same problem, until I realized that the decimal separator was set as (,) instead of (.) in the default settings. Once I changed that, everything worked fine.
If your "numbers" are being detected as text, you can use VALUE() to make sure Excel understands that it is actually a number.
A1: `1.23E+10 (this is a string)
B1: =VALUE(A1)
=12300000000
C1: 1.23E+10 (this is a number)
D1: =IF(B1==C1,"It worked", "Uh Oh")
=It Worked (for me anyway)
I'm not sure what the comma in your scientific number will do so might want to have the function replace them if there not required.
See Kenneth Hobs' answer here: http://www.vbaexpress.com/forum/showthread.php?42119-Solved-Convert-exponential-format-to-a-number
Open your Excel File, Press Alt + f11 to open the VBA screen,
Go to Insert > Module, Copy and Paste Kenneth's code:
Sub Expo()
Dim cell As Range, s() As String, lng As Long, n As Integer
For Each cell In Selection
With cell
If Not VarType(.Value2) = vbString Then GoTo NextCell
s() = Split(cell.Value2, "E")
.Value2 = s(0) * 1 * (1 * 10 ^ s(1)) 'ePart(s(1))
.NumberFormat = "General"
.EntireColumn.AutoFit
End With
NextCell:
Next cell
End Sub
You can now run it as a macro to convert selected cells. Or if you want it as a function copy this code instead:
Function Expo(cell As Range)
Dim s() As String
With cell
If VarType(.Value2) = vbString Then
s() = Split(.Value2, "E")
Expo = s(0) * 1 * (1 * 10 ^ s(1)) 'ePart(s(1))
End If
End With
End Function
This way you can use it as a normal function in excel eg =Expo(A1)
As I mentioned in the comments above though, you will have already lost some degree of accuracy when the original number was converted to scientific notation. The best solution is to get the originating program to write the proper numbers into the text file if you can.
Open a new word document and try Pasting the web content in word first, the copy this content from the word document and paste special in excel, as text. This simple solution worked for me
Open a new blank Excel, then go to Data > From Text, this way you can import text and designate which format you want to convert to. On the Text Import Wizard page, select either Delimited or Fixed width (I am not sure how your original text file look like but generally it should be Delimited. On the next page, pick a Delimiter or enter one in Others. On step 3, you should see the data listed below and the data format on the upper left. Pick General for those columns that you believe should not be Text. This should fix your problem.
My case was stubborn, no response to Paste Special or CLEAN(). Finally resolved by copying the offending column of Excel data and pasting into new Notepad++ doc. This revealed a leading "?" in all the bad numbers (apparently some non-printing character). Used Search > Replace to find all "?" and replace with nothing. Edit > Select All, copy to a new Excel column, and voilà!
There may be hidden characters. Trailing/leading spaces may not visible and hence erroneously be neglected. If there is trailing/leading Space characters with numeric values, excel consider it as text.
Copy contents problematic cells to MS-Word [(Select problematic cells and copy them to MS-Word)] and check any hidden characters, Remove hidden characters with "find"/"replace" functionality.
I was having issues with numbers from PPT (e.g. ($3,000))pasted to excel. Tried multiple different ways to get the text to recognize including find replacing parens, commas, $ signs to blank and trying to format so excel could run formulas. The only option that worked was to paste to Word first then paste value to excel which worked without any additional formatting steps. Surprised I could not do it all within excel though. Maybe there's another way
Select all the cells to convert to a number.
|Data| Menu Tab > Data Tools > [Text to columns]
Delimited. [Next]
Deselect all "Delimiters". [Next]
"Column data format" > General
[Finish]
Verify by using =ISNUMBER(C16) in an spare cell, where C16 is a sample cell. Should now return TRUE.
This happened to me lately. I had forgotten that I had set formula recalculation to manual. The weird thing is that it was returing FALSE when initially created (which was correct) but given the test depended on the value of other cells that, when changed, did not trigger the change in the cell with the isnumber() formula.
Pressing F9 "fixed" my problem (and my ignorance).

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