Logo 
Search:

MS Office Answers

Ask Question   UnAnswered
Home » Forum » MS Office       RSS Feeds
  Question Asked By: Lorraine Stephens   on Mar 01 In MS Office Category.

  
Question Answered By: Rory Anderson   on Mar 01

You mentioned you were new to VBA. Perhaps you don’t yet understand how the
Format function works.



The Format function is used to take a value and convert  it to a specified
String representation. So if you have a date  variable:



Dim varDateOfBirth Ad Date



And if you set its value to 30 April 2007 like this (in the US):



varDateOfBirth = “4/30/2007”



And you want to convert it to a String so you can display it to the user,
and have this string in a certain format, you can use the Format function:



Dim strDateOfBirth as String

strDateOfBirth = Format(varDateOfBirth, “mm/dd/yyyy”)



In this specific case, this will make sure it prints out with two digits for
both the month and day, like “04/30/2007” instead of just “4/30/2007”.



By the way, it is more customary to use “var” as a variable name prefix if
the variable is of type Variant, like this:



Dim varDateOfBirth As Variant



It would be more common for a Date to use the prefix dt or dat like this:



Dim dtDateOfBirth As Date

Dim datDateOfBirth As Date



Additionally, double quotes are the standard delimiters for Strings, and
they work for Dates, but it is more common for Dates to use hash symbols, as
in:



dtDateOfBirth = #4/30/2007#

instead of

dtDateOfBirth = “4/30/2007”



You do not use the Format function to specify a formatting template, as you
said, that you can apply to a variable once and think it stays that way –
the Format function generates a String value of a specified format when you
call it – that one time.



Also, you mentioned in your Subject something about the UK. If you prefer
the day  to come before the month, you can use:



strDateOfBirth = Format(dtDateOfBirth, “dd/mm/yyyy”)



There are also predefined date formats you can make use of that would
automatically adjust based on your computer’s locale setting so the same
code could be used in the US or the UK without any code changes.

Share: 

 

This Question has 5 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on US/UK Date conflict Or get search suggestion and latest updates.


Tagged: