Vba word формат числа

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Format function (Visual Basic for Applications)

vblr6.chm1008925

vblr6.chm1008925

office

67f60abf-0c77-49ec-924f-74ae6eb96ea8

08/14/2019

high

Returns a Variant (String) containing an expression formatted according to instructions contained in a format expression.

[!includeAdd-ins note]

Syntax

Format(Expression, [ Format ], [ FirstDayOfWeek ], [ FirstWeekOfYear ])

The Format function syntax has these parts.

Part Description
Expression Required. Any valid expression.
Format Optional. A valid named or user-defined format expression.
FirstDayOfWeek Optional. A constant that specifies the first day of the week.
FirstWeekOfYear Optional. A constant that specifies the first week of the year.

Settings

The firstdayofweek argument has these settings.

Constant Value Description
vbUseSystem 0 Use NLS API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

The firstweekofyear argument has these settings.

Constant Value Description
vbUseSystem 0 Use NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the year.
vbFirstFullWeek 3 Start with the first full week of the year.

Remarks

To format Do this
Numbers Use predefined named numeric formats or create user-defined numeric formats.
Dates and times Use predefined named date/time formats or create user-defined date/time formats.
Date and time serial numbers Use date and time formats or numeric formats.
Strings Create your own user-defined string formats.

Format truncates format to 257 characters.

If you try to format a number without specifying format, Format provides functionality similar to the Str function, although it is internationally aware. However, positive numbers formatted as strings using Format don’t include a leading space reserved for the sign of the value; those converted using Str retain the leading space.

If you are formatting a non-localized numeric string, you should use a user-defined numeric format to ensure that you get the look you want.

[!NOTE]
If the Calendar property setting is Gregorian and format specifies date formatting, the supplied expression must be Gregorian. If the Visual Basic Calendar property setting is Hijri, the supplied expression must be Hijri.

If the calendar is Gregorian, the meaning of format expression symbols is unchanged. If the calendar is Hijri, all date format symbols (for example, dddd, mmmm, yyyy ) have the same meaning but apply to the Hijri calendar. Format symbols remain in English; symbols that result in text display (for example, AM and PM) display the string (English or Arabic) associated with that symbol. The range of certain symbols changes when the calendar is Hijri.

Date symbols

Symbol Range
d 1-31 (Day of month, with no leading zero)
dd 01-31 (Day of month, with a leading zero)
w 1-7 (Day of week, starting with Sunday = 1)
ww 1-53 (Week of year, with no leading zero; Week 1 starts on Jan 1)
m 1-12 (Month of year, with no leading zero, starting with January = 1)
mm 01-12 (Month of year, with a leading zero, starting with January = 01)
mmm Displays abbreviated month names (Hijri month names have no abbreviations)
mmmm Displays full month names
y 1-366 (Day of year)
yy 00-99 (Last two digits of year)
yyyy 100-9999 (Three- or Four-digit year)

Time symbols

Symbol Range
h 0-23 (1-12 with «AM» or «PM» appended) (Hour of day, with no leading zero)
hh 00-23 (01-12 with «AM» or «PM» appended) (Hour of day, with a leading zero)
n 0-59 (Minute of hour, with no leading zero)
nn 00-59 (Minute of hour, with a leading zero)
m 0-59 (Minute of hour, with no leading zero). Only if preceded by h or hh
mm 00-59 (Minute of hour, with a leading zero). Only if preceded by h or hh
s 0-59 (Second of minute, with no leading zero)
ss 00-59 (Second of minute, with a leading zero)

Example

This example shows various uses of the Format function to format values using both named formats and user-defined formats. For the date separator (/), time separator (:), and AM/ PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time format and short date format of the code locale are used. When displayed by running code, the short time format and short date format of the system locale are used, which may differ from the code locale. For this example, English/U.S. is assumed. MyTime and MyDate are displayed in the development environment using current system short time setting and short date setting.

Dim MyTime, MyDate, MyStr
MyTime = #17:04:23#
MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")    ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss am/pm")    ' Returns "05:04:23 pm".
MyStr = Format(MyTime, "hh:mm:ss AM/PM")    ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")    ' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23)    ' Returns "23".

' User-defined formats.
MyStr = Format(5459.4, "##,##0.00")    ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00")    ' Returns "334.90".
MyStr = Format(5, "0.00%")    ' Returns "500.00%".
MyStr = Format("HELLO", "<")    ' Returns "hello".
MyStr = Format("This is it", ">")    ' Returns "THIS IS IT".

Different formats for different numeric values

A user-defined format expression for numbers can have from one to four sections separated by semicolons. If the format argument contains one of the named numeric formats, only one section is allowed.

If you use The result is
One section only The format expression applies to all values.
Two sections The first section applies to positive values and zeros, the second to negative values.
Three sections The first section applies to positive values, the second to negative values, and the third to zeros.
Four sections The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values.

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays «Zero» if the value is zero.

Different formats for different string values

A format expression for strings can have one section or two sections separated by a semicolon (;).

If you use The result is
One section only The format applies to all string data.
Two sections The first section applies to string data, the second to Null values and zero-length strings («»).

Named date/time formats

The following table identifies the predefined date and time format names.

Format name Description
General Date Display a date and/or time, for example, 4/3/93 05:34 PM. If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system settings.
Long Date Display a date according to your system’s long date format.
Medium Date Display a date using the medium date format appropriate for the language version of the host application.
Short Date Display a date using your system’s short date format.
Long Time Display a time using your system’s long time format; includes hours, minutes, seconds.
Medium Time Display time in 12-hour format using hours and minutes and the AM/PM designator.
Short Time Display a time using the 24-hour format, for example, 17:45.

Named numeric formats

The following table identifies the predefined numeric format names.

Format name Description
General Number Display number with no thousand separator.
Currency Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.
Fixed Display at least one digit to the left and two digits to the right of the decimal separator.
Standard Display number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
Scientific Use standard scientific notation.
Yes/No Display No if number is 0; otherwise, display Yes.
True/False Display False if number is 0; otherwise, display True.
On/Off Display Off if number is 0; otherwise, display On.

User-defined string formats

Use any of the following characters to create a format expression for strings.

Character Description
@ Character placeholder. Display a character or a space. If the string has a character in the position where the at symbol (@) appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
& Character placeholder. Display a character or nothing. If the string has a character in the position where the ampersand (&) appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
< Force lowercase. Display all characters in lowercase format.
> Force uppercase. Display all characters in uppercase format.
! Force left to right fill of placeholders. The default is to fill placeholders from right to left.

User-defined date/time formats

The following table identifies characters you can use to create user-defined date/time formats.

Character Description
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.
(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
c Display the date as ddddd and display the time as ttttt, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.
d Display the day as a number without a leading zero (1–31).
dd Display the day as a number with a leading zero (01–31).
ddd Display the day as an abbreviation (Sun–Sat). Localized.
dddd Display the day as a full name (Sunday–Saturday). Localized.
ddddd Display the date as a complete date (including day, month, and year), formatted according to your system’s short date format setting. The default short date format is m/d/yy.
dddddd Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. The default long date format is mmmm dd, yyyy.
w Display the day of the week as a number (1 for Sunday through 7 for Saturday).
ww Display the week of the year as a number (1–54).
m Display the month as a number without a leading zero (1–12). If m immediately follows h or hh, the minute rather than the month is displayed.
mm Display the month as a number with a leading zero (01–12). If m immediately follows h or hh, the minute rather than the month is displayed.
mmm Display the month as an abbreviation (Jan–Dec). Localized.
mmmm Display the month as a full month name (January–December). Localized.
q Display the quarter of the year as a number (1–4).
y Display the day of the year as a number (1–366).
yy Display the year as a 2-digit number (00–99).
yyyy Display the year as a 4-digit number (100–9999).
h Display the hour as a number without a leading zero (0–23).
hh Display the hour as a number with a leading zero (00–23).
n Display the minute as a number without a leading zero (0–59).
nn Display the minute as a number with a leading zero (00–59).
s Display the second as a number without a leading zero (0–59).
ss Display the second as a number with a leading zero (00–59).
ttttt Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is h:mm:ss.
AM/PM Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.
am/pm Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.
A/P Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.
a/p Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.
AMPM Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. The default format is AM/PM. If your system is set to 24-hour clock, the string is typical set to a zero-length string.

User-defined numeric formats

The following table identifies characters you can use to create user-defined number formats.

Character Description
None Display the number with no formatting.
(0) Digit placeholder. Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.
(#) Digit placeholder. Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position. This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren’t displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.
(.) Decimal placeholder. In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. To display a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.
(%) Percentage placeholder. The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.
(,) Thousand separator. In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means «scale the number by dividing it by 1000, rounding as needed.» For example, you can use the format string «##0,,» to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.
(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
(E- E+ e- e+) Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents.
— + $ ( ) Display a literal character. To display a character other than one of those listed, precede it with a backslash () or enclose it in double quotation marks (» «).
() Display the next character in the format string. To display a character that has special meaning as a literal character, precede it with a backslash (). The backslash itself isn’t displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\). Examples of characters that can’t be displayed as literal characters are the date-formatting and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, /, and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).
(«ABC») Display the string inside the double quotation marks (» «). To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a quotation mark («)).

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

Currencies and numbers being displayed on a board

Short introduction to strings

A string is a sequence or group of characters of any length that may or may not have a semantic meaning in language. It can consist of several characters like numbers, letters in both lowercase and uppercase, punctuation, and symbols.

Examples of strings:

1. “Testme123”

2. “Daniel Dozen”

3. “Please enter your name”

4. “Christmas falls on 25th December of every year”

5. “@$#%$%^”

6. “234325fdgdgfd”

Formatting a string

From the above examples we can infer that each character in a string can be a unique datatype, such as “lowercase letter,” “number,” “uppercase letter,” “symbol,” or “punctuation .” In your programmin,g there may be situations you need the string to be a particular format.

For example:

  1. A textbox might expect date to be entered in exactly “mm-dd-yyyy” format.
  2. Numbers entered might need to be displayed along with a currency symbol.
  3. The percentage symbol can be used along with numbers to indicate values like an interest rate.
  4. Decimals can be used with numbers for easy reading.

This formatting can be done using the “Format” functions offered by Visual Basic for Applications.

The Format function

This function offered by the VBA library can be categorized as a string or date function. It converts the given expression to the expected format and returns it as a string.

Syntax

Format ( < string expression > , [ format ] )

Where

< string expression > is the string that needs to be formatted and

[ format ] is format that needs to be applied to the specified string expression. This is an optional parameter, so it’s enclosed with square brackets.

The format parameter can either be a user-defined format or it can be a named format predefined by Excel. Here are some named formats which are provided by MS Excel.

Format Explanation
General This is the default number format that MS Excel applies if we simply type a number. In most of the cases, the numbers which are formatted with the “General” format are displayed the same way we type them. However, if the width of the cell is not sufficient to display the entire number, the “General” format rounds off the numbers with decimals. This number format also uses “scientific  notation” (exponential form) for high-value or large numbers that have 12 or more digits.
Currency This is used for monetary values and displays the currency symbol with numbers. The default currency symbol used is “$”. There are options to specify the number of decimal places that we want to use. For example, we may want to use a thousands separator. We can also specify if we want to display number is negative depending on their value.
Fixed This format displays at least 1 digit to the left side of the decimal place and 2 digits to the right side of the decimal place.
Standard This format displays the thousand separators, at least 1 digit to the left side of the decimal place, and 2 digits to the right side of the decimal place.
Percent This format displays a percent value – (ie), a number divided by 100 with a % sign. It displays two digits to the right of the decimal place.
Scientific Indicates scientific notation. It’s a number in exponential notation, which replaces a part of the number with “E+n”, where E (stands for Exponent) and multiplies the preceding number by “10” to the nth power. For example, a two decimal Scientific format displays 12345678901 as 1.23E+10, which is 1.23 times 10 to the 10th power. We can specify the number of decimal places that we want to use.
Yes/No This format displays “No” if the number is 0 and “Yes” if the number is not 0.
True/False This format displays “False” if the number is 0 and “True” if the number is not 0.
On/Off This format displays “Off” if the number is 0 and “On” if the number is not 0.
General Date This format displays date and time serial numbers as date values, based on the type and location we specify. Date formats which begin with an asterisk symbol (*) respond to changes in the regional date and time settings already set in the system’s Control Panel. Formats which do not have an asterisk are not affected by settings in the Control Panel.
Long Date This format displays a date value based on long date setting of our system
Medium Date This format displays a date value based on meduim date setting of our system
Short Date This format displays a date value based on short date setting of our system
Time This format displays date and time serial numbers as time values, depending on the type and location we specify. Time formats that begin with an asterisk symbol (*) respond to changes in the regional date and time settings already set in the system’s Control Panel. Formats which do not have an asterisk are not affected by settings in the Control Panel.
Long Time This format displays a date value based on long time setting of our system
Medium Time This format displays a date value based on meduim time setting of our system
Short Time This format displays a date value based on short time setting of our system
Number This is used in general to display numbers. We can specify the number of decimal places that we would like to use. For example , we may want to use a thousands separator. We can also specify if we want to display number is negative depending on their value.
Accounting This is also used for monetary values . It aligns the decimal points of numbers and currency symbols in a column.
Fraction It displays a number as a fraction depending on the type of fraction we specify.

Examples using the Format function

Using a custom format to format numbers

Sub format_demo()

' declare variable
Dim str_num

' use the format function and assign value
str_num = Format("510.3", "#,##0.00")

' print the value - it should be '510.30'
Debug.Print str_num

End Sub

Predefined formatting used on numbers

This example covers formatting numbers with percentage, currency and decimals.

Sub format_demo_predef()


'declare variables
Dim str_std, str_per, str_cur, str_shdt

'Assign values using the format function
str_std = Format("611.6", "Standard")
str_per = Format("0.982", "Percent")
str_cur = Format("1369.5", "Currency")

'Print the results
Debug.Print str_std ' Result should be : '611.60'
Debug.Print str_per ' Result should be : '98.20%'
Debug.Print str_cur ' Result should be : '$1,369.50' provided a currency symbol is already set.
End Sub

Sample program to show the format function to display dates

This program displays dates in both short date and long date format. There are some predefined formats the user may be interested in.

Sub format_demo_predef()
' declare variables
Dim str_shdt, str_lgdt

' Assign values using the format function
str_shdt = Format("Sep 9, 2013", "Short Date")
str_lgdt = Format("Sep 9, 2013", "Long Date")

' Print the results
Debug.Print str_shdt ' Result should be : '09-09-2013' ( depends on system setting in control panel )
Debug.Print str_lgdt ' Result should be : '09 September 2013' ( depends on system setting in control panel )

End Sub

Conclusion

The format function can be widely used to display data (strings, numbers, or a combination of both ) the way we want. There may be scenarios that use queries to store or retrieve data from backend and compare it with some other data that is displayed on user forms or webpages.

These comparisons can result in failures even if the data match, just because the format of data being compared is different. In such situations it is a good idea to use this Format function and convert the data that’s being compared to a common format. This will provide you with more reliable results.

Excel VBA Format Function

Format function in VBA one may use to format the given values in the desired format. For example, one can use this function for formatting dates or numbers or any trigonometric values. This function has two mandatory arguments: input taken in the form of a string, and the second argument is the type of format we want to use. For example, if we use Format (.99,” Percent”) this will give us the result as 99%.

In VBA, we need to use the function “FORMAT” to apply the format to cells. Excel formattingFormatting is a useful feature in Excel that allows you to change the appearance of the data in a worksheet. Formatting can be done in a variety of ways. For example, we can use the styles and format tab on the home tab to change the font of a cell or a table.read more is one of the important concepts to master. We all use the common formatting techniques in our daily work: date, time, number, and other important formatting codes. We press the format excel cellFormatting cells is an important technique to master because it makes any data presentable, crisp, and in the user’s preferred format. The formatting of the cell depends upon the nature of the data present.read more option in regular Excel worksheets and perform the formatting duty by applying the appropriate formatting code. However, in VBA, this is not as straightforward as our worksheet technique.

Table of contents
  • Excel VBA Format Function
    • Syntax
    • How to Use?
      • #1 – Currency Format
      • #2 – Fixed Format
      • #3 – Percent Format
      • #4 – User-Defined Formats
      • #5 – Date FORMAT
    • Things to Remember
    • Recommended Articles

VBA-Format

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Format (wallstreetmojo.com)

Syntax

VBA Format Formula

  • Expression: This is nothing but the value we want to format. In VAB technicality, it is called Expression.
  • [Format]: What format do you want to apply to the selected expression? We have two kinds of formatting here: user-defined format and built-in format.
  • Here, we have VBA date, number, and text formats.
  • VBA date formats have a short date, long date, medium date, and general date.
  • Number formats have currency, standard, percentage, scientific, yes or no, true or false, and on or off.
  • [First Day of the Week]: What is the first day of your week? We can select any day from the list. Below is the list of days and appropriate codes.

VBA Format Table 1

  • [First Week of the Year]: What is the year’s first week? It specifies the week it should use as the year’s first week.

VBA Format Table 2

How to Use?

You can download this VBA Format Template here – VBA Format Template

Let us apply this function practically to understand the functionality of the FORMAT function. Assume you have the number 8072.56489. You want to apply number formatting to it. Follow the below steps to apply number formatting to it.

Step 1: Start an excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
and define the variable as a “string” data type.

Code:

Sub Worksheet_Function_Example1()

  Dim K As String

End Sub

VBA Format Example 1

Step 2: Assign a value to k as our number, 8072.56489.

Code:

Sub Worksheet_Function_Example1()
  Dim K As String

  K = 8072.56489

End Sub

VBA Format Example 1-1

Step 3: Show the “k” value in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub Worksheet_Function_Example1()
  Dim K As String

  K = 8072.56489
  MsgBox K

End Sub

VBA Format Example 1-2

Step 4: If you run this macro, we will get the below result.

VBA Format Example 1-3

The result is as it is, we assigned the value to variable “k.” But we need to apply some formatting to this number to make it beautiful.

Step 5: Instead of directly assigning a value to “k, let us use the FORMAT function.

Code:

Sub Worksheet_Function_Example1()
  Dim K As String

  K = Format(
  MsgBox K

End Sub

VBA Format Example 1-4

Step 6: Now, for Expression, assign the number 8072.56489.

Code:

Sub Worksheet_Function_Example1()
  Dim K As String

  K = Format(8072.56489,
  MsgBox K

End Sub

VBA Format Example 1-5

Step 7: We can use a built-in format or our own formatting code in the formatting option. Now, we will use a built-in formatting style as “Standard.”

Code:

Sub Worksheet_Function_Example1()
  Dim K As String

  K = Format(8072.56489, "Standard")
  MsgBox K

End Sub

VBA Format Example 1-6
Step 8: Now, run this code and see the result of the message box.

VBA Format Example 1-7

We have comma (,) as thousand separators and decimal rounds up to two digits only.

Like this, we can use many other built-in formatting styles to apply the formatting. Below are some of the codes we have applied.

#1 – Currency Format

Code:

Sub Worksheet_Function_Example2()
  Dim K As String

  K = Format(8072.56489, "Currency")
  MsgBox K

End Sub

VBA Currency Format

Result:

VBA Currency Format 1

#2 – Fixed Format

Code:

Sub Worksheet_Function_Example3()
  Dim K As String

  K = Format(8072.56489, "Fixed")
  MsgBox K

End Sub

Fixed example 1

Result:

Fixed example 1-1

#3 – Percent Format

Code:

Sub Worksheet_Function_Example4()
  Dim K As String

  K = Format(8072.56489, "Percent")
  MsgBox K

End Sub

Percent Format

Result:

Percent Format 1

#4 – User-Defined Formats

Now, we will see some of the user-defined formats.

Code:

Sub Worksheet_Function_Example5()
  Dim K As String

  K = Format(8072.56489, "#.##")
  MsgBox K

End Sub

Example 5

Result:

Example 5-1

Code:

Sub Worksheet_Function_Example5()
  Dim K As String

  K = Format(8072.56489, "#,##.##")
  MsgBox K

End Sub

Example 5-2

Result:

Example 5-3

#5 – Date FORMAT

We have seen some important numbers of formatting techniques. We will have to use the FORMAT function to format the date in VBA.To format the date in VBA, we use the in-built FORMAT function that converts a date expression into the required format. In order to perform the function, one must enter a valid expression and format type.read more

We have written code to show the result of the date through the variable.

Code:

Sub Worksheet_Function_Example6()
  Dim K As String

  K = 13 - 3 - 2019
  MsgBox K

End Sub

When we run this code, we would not get an accurate date. Rather, the result is pathetic.

Date Function 1

We need to assign the date format to get accurate dates. So, we first need to supply the date in double quotes and apply the date format.

Code:

Sub Worksheet_Function_Example6()
  Dim K As String

  K = Format("10 - 3 - 2019", "Long Date")
  MsgBox K

End Sub

We run this code now. We will get a proper long date.

Date Function 1-1

The “Long Date” is a built-in format. Similarly, you can use the “Short Date” and “Medium Date” options.

Things to Remember

  • The value returned by the FORMAT function is the string.
  • We can also use our date, time, and number formatting codes, like how we use them in worksheet formatting.
  • The FORMAT is a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more available only in VBA, not in the worksheet.

Recommended Articles

This article has been a guide to VBA Format Function. Here, we learned how to use VBA Format Function for currency, fixed, percentage, and date formatting, along with some practical examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA Data Type
  • VBA DIR Function
  • VBA MOD
  • Create VBA InputBox

Like this post? Please share to your friends:
  • Vba word формат таблицы
  • Vba word формат по образцу
  • Vba word удалить строку текста
  • Vba word удалить столбец таблицы
  • Vba word удалить символ