1

I'd like to achieve the result seen in A1. How come line 3 doesn't output the same result as line 1 & 2 even though the format is the same - yyyy-mm-dd hh:mm:ss?

Does this have anything to do with regional settings?

enter image description here

1   Range("A1").Value2 = Now
2   Range("A1").NumberFormat = "yyyy-mm-dd hh:mm:ss"
3   Range("B1").Value2 = Format(Now, "yyyy-mm-dd hh:mm:ss")
1
  • 1
    I don't have the why (I'm guessing excel is trying to be smart for you) but if you have date data, please keep it as date and modify the presentation through NumberFormat Commented Nov 29, 2021 at 16:58

2 Answers 2

1

That is because:

A1: You set a Date value and apply a specific format for display.

B1: You format a Date value to Text, set that as the value, but the cell has been applied no specific format, thus Excel sees the text date as a date value and casts it to a true Date value, which is displayed with your default (German?) date format.

To force the text date to be read as text, you could prefix it with a quote:

Range("A1").Value2 = Now
Range("A1").NumberFormat = "yyyy-mm-dd hh:mm:ss"
Range("B1").Value2 = Format(Now, "yyyy-mm-dd hh:mm:ss")
Range("C1").Value2 = Format(Now, "\'yyyy-mm-dd hh:mm:ss")

Output (Danish localisation):

enter image description here

Note, that C1 is text (left-aligned).

Sign up to request clarification or add additional context in comments.

1 Comment

I see. This answers the question. Thank you @Gustav
0

Why you not set, before or after, your cell formatting with a Range?

Example:

Range("A1:Z1").NumberFormat = "yyyy-mm-dd hh:mm:ss"
Range("A1").Value2 = Now
Range("B1").Value2 = Now

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.