<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="VB6Parse Library Reference - format - String">
<title>format - String - VB6Parse Library Reference</title>
<link rel="stylesheet" href="../../../assets/css/style.css">
<link rel="stylesheet" href="../../../assets/css/docs-style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<script src="../../../assets/js/theme-switcher.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/vbnet.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<body>
<header class="docs-header">
<div class="container">
<h1><a href="../../../index.html">VB6Parse</a> / <a href="../../../library/index.html">Library</a> / <a href="../../../library/functions/string/index.html">String</a> / format</h1>
<p class="tagline">VB6 Library Reference</p>
</div>
</header>
<nav class="docs-nav">
<div class="container">
<a href="../../../index.html">Home</a>
<a href="../../../library/index.html">Library Reference</a>
<a href="../../../documentation.html">Documentation</a>
<a href="https://docs.rs/vb6parse" target="_blank">API Docs</a>
<a href="https://github.com/scriptandcompile/vb6parse" target="_blank">GitHub</a>
<button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
<span class="theme-icon">🌙</span>
</button>
</div>
</nav>
<main class="container">
<article class="library-item">
<h1 id="format-function">Format Function</h1>
<p>Returns a <code>Variant</code> (<code>String</code>) containing an expression formatted according to instructions contained in a format expression.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">Format(expression[, format[, firstdayofweek[, firstweekofyear]]])</code></pre>
<h2 id="parameters">Parameters</h2>
<ul>
<li><strong>expression</strong>: Required. Any valid expression to be formatted.</li>
<li><strong>format</strong>: Optional. A valid named or user-defined format expression.</li>
<li><strong>firstdayofweek</strong>: Optional. A constant that specifies the first day of the week (vbSunday=1, vbMonday=2, etc.).</li>
<li><strong>firstweekofyear</strong>: Optional. A constant that specifies the first week of the year.</li>
</ul>
<h2 id="return-value">Return Value</h2>
<p>Returns a <code>Variant</code> of subtype <code>String</code> containing the formatted expression. If format is omitted,
<code>Format</code> returns a string similar to the <code>Str</code> function.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>Format</code> function is one of VB6's most versatile functions for converting values to
formatted strings. It supports numeric formatting, date/time formatting, and string formatting
with extensive control over output appearance.
<strong>Important Characteristics:</strong>
- Supports named formats (e.g., "General Number", "Currency", "Short Date")
- Supports user-defined format strings with placeholders
- Numeric formats: 0, #, ., ,, %, E, etc.
- Date/time formats: d, m, y, h, n, s, etc.
- String formats: @, &, <, >, !
- Returns empty string if expression is Null
- Locale-aware (respects regional settings)
- Can create custom formats with multiple sections
- Supports scientific notation
- Handles positive, negative, zero, and null values separately</p>
<h2 id="named-formats">Named Formats</h2>
<h3 id="numeric-named-formats">Numeric Named Formats</h3>
<ul>
<li><strong>General Number</strong>: No thousand separator; displays as entered</li>
<li><strong>Currency</strong>: Thousand separator, 2 decimal places, currency symbol</li>
<li><strong>Fixed</strong>: At least one digit left of decimal, 2 digits right</li>
<li><strong>Standard</strong>: Thousand separator, 2 decimal places</li>
<li><strong>Percent</strong>: Multiplies by 100, adds percent sign, 2 decimal places</li>
<li><strong>Scientific</strong>: Standard scientific notation</li>
</ul>
<h3 id="datetime-named-formats">Date/Time Named Formats</h3>
<ul>
<li><strong>General Date</strong>: Short date and time if time ≠ midnight</li>
<li><strong>Long Date</strong>: Full date (e.g., "Wednesday, January 1, 2025")</li>
<li><strong>Medium Date</strong>: Date with abbreviated month (e.g., "01-Jan-25")</li>
<li><strong>Short Date</strong>: Locale-specific short date (e.g., "1/1/2025")</li>
<li><strong>Long Time</strong>: Full time with seconds (e.g., "1:30:00 PM")</li>
<li><strong>Medium Time</strong>: Time in 12-hour format (e.g., "1:30 PM")</li>
<li><strong>Short Time</strong>: Time in 24-hour format (e.g., "13:30")</li>
</ul>
<h2 id="typical-uses">Typical Uses</h2>
<ul>
<li>Format numbers with specific decimal places</li>
<li>Add thousand separators to large numbers</li>
<li>Format currency values</li>
<li>Display percentages</li>
<li>Format dates and times for display</li>
<li>Align text in reports</li>
<li>Create fixed-width output</li>
<li>Zero-pad numbers</li>
<li>Convert values to specific string representations</li>
</ul>
<h2 id="examples">Examples</h2>
<h3 id="basic-numeric-formatting">Basic Numeric Formatting</h3>
<pre><code class="language-vbnet">Dim value As Double
value = 1234.567
' Named formats
Debug.Print Format(value, "General Number") ' 1234.567
Debug.Print Format(value, "Currency") ' $1,234.57
Debug.Print Format(value, "Fixed") ' 1234.57
Debug.Print Format(value, "Standard") ' 1,234.57
Debug.Print Format(value, "Percent") ' 123456.70%
Debug.Print Format(value, "Scientific") ' 1.23E+03
' Custom formats
Debug.Print Format(value, "0.00") ' 1234.57
Debug.Print Format(value, "#,##0.00") ' 1,234.57
Debug.Print Format(value, "000000.00") ' 001234.57</code></pre>
<h3 id="datetime-formatting">Date/Time Formatting</h3>
<pre><code class="language-vbnet">Dim dt As Date
dt = #1/15/2025 3:45:30 PM#
' Named formats
Debug.Print Format(dt, "General Date") ' 1/15/2025 3:45:30 PM
Debug.Print Format(dt, "Long Date") ' Wednesday, January 15, 2025
Debug.Print Format(dt, "Short Date") ' 1/15/2025
Debug.Print Format(dt, "Long Time") ' 3:45:30 PM
Debug.Print Format(dt, "Short Time") ' 15:45
' Custom formats
Debug.Print Format(dt, "yyyy-mm-dd") ' 2025-01-15
Debug.Print Format(dt, "dd/mm/yyyy") ' 15/01/2025
Debug.Print Format(dt, "hh:nn:ss") ' 03:45:30
Debug.Print Format(dt, "dddd, mmmm d, yyyy") ' Wednesday, January 15, 2025</code></pre>
<h3 id="string-formatting">String Formatting</h3>
<pre><code class="language-vbnet">Dim text As String
text = "hello"
Debug.Print Format(text, ">") ' HELLO (uppercase)
Debug.Print Format(text, "<") ' hello (lowercase)
Debug.Print Format(text, "@@@@@@@@@@") ' 00000hello (right-aligned)</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="format-currency-with-symbol">Format Currency with Symbol</h3>
<pre><code class="language-vbnet">Function FormatCurrency(amount As Double) As String
FormatCurrency = Format(amount, "$#,##0.00")
End Function
' Usage
Debug.Print FormatCurrency(1234.56) ' $1,234.56
Debug.Print FormatCurrency(-500) ' $-500.00</code></pre>
<h3 id="zero-pad-numbers">Zero-Pad Numbers</h3>
<pre><code class="language-vbnet">Function PadWithZeros(num As Long, totalDigits As Integer) As String
Dim formatStr As String
formatStr = String(totalDigits, "0")
PadWithZeros = Format(num, formatStr)
End Function
' Usage
Debug.Print PadWithZeros(42, 6) ' 000042
Debug.Print PadWithZeros(7, 3) ' 007</code></pre>
<h3 id="format-file-sizes">Format File Sizes</h3>
<pre><code class="language-vbnet">Function FormatFileSize(bytes As Long) As String
Const KB = 1024
Const MB = 1048576
Const GB = 1073741824
If bytes >= GB Then
FormatFileSize = Format(bytes / GB, "0.00") & " GB"
ElseIf bytes >= MB Then
FormatFileSize = Format(bytes / MB, "0.00") & " MB"
ElseIf bytes >= KB Then
FormatFileSize = Format(bytes / KB, "0.00") & " KB"
Else
FormatFileSize = Format(bytes, "#,##0") & " bytes"
End If
End Function</code></pre>
<h3 id="format-phone-numbers">Format Phone Numbers</h3>
<pre><code class="language-vbnet">Function FormatPhoneNumber(phoneNum As String) As String
' Remove non-numeric characters
Dim cleaned As String
Dim i As Long
For i = 1 To Len(phoneNum)
If IsNumeric(Mid(phoneNum, i, 1)) Then
cleaned = cleaned & Mid(phoneNum, i, 1)
End If
Next i
' Format as (XXX) XXX-XXXX
If Len(cleaned) = 10 Then
FormatPhoneNumber = "(" & Left(cleaned, 3) & ") " & _
Mid(cleaned, 4, 3) & "-" & _
Right(cleaned, 4)
Else
FormatPhoneNumber = phoneNum
End If
End Function</code></pre>
<h3 id="custom-date-display">Custom Date Display</h3>
<pre><code class="language-vbnet">Function FormatDateFriendly(dt As Date) As String
Dim daysDiff As Long
daysDiff = DateDiff("d", dt, Date)
Select Case daysDiff
Case 0
FormatDateFriendly = "Today at " & Format(dt, "h:nn AM/PM")
Case 1
FormatDateFriendly = "Yesterday at " & Format(dt, "h:nn AM/PM")
Case 2 To 6
FormatDateFriendly = Format(dt, "dddd") & " at " & _
Format(dt, "h:nn AM/PM")
Case Else
FormatDateFriendly = Format(dt, "mmmm d, yyyy")
End Select
End Function</code></pre>
<h3 id="format-percentages">Format Percentages</h3>
<pre><code class="language-vbnet">Function FormatPercent(value As Double, decimals As Integer) As String
Dim formatStr As String
formatStr = "0." & String(decimals, "0") & "%"
FormatPercent = Format(value, formatStr)
End Function
' Usage
Debug.Print FormatPercent(0.1234, 2) ' 12.34%
Debug.Print FormatPercent(0.5, 0) ' 50%</code></pre>
<h3 id="format-decimal-places">Format Decimal Places</h3>
<pre><code class="language-vbnet">Function FormatDecimal(value As Double, places As Integer) As String
Dim formatStr As String
If places = 0 Then
formatStr = "0"
Else
formatStr = "0." & String(places, "0")
End If
FormatDecimal = Format(value, formatStr)
End Function
' Usage
Debug.Print FormatDecimal(3.14159, 2) ' 3.14
Debug.Print FormatDecimal(100.7, 0) ' 101</code></pre>
<h3 id="align-text-in-reports">Align Text in Reports</h3>
<pre><code class="language-vbnet">Sub PrintReport()
Debug.Print "Name", "Amount"
Debug.Print String(40, "-")
Debug.Print "Item 1", Format(1234.56, "$#,##0.00")
Debug.Print "Item 2", Format(78.9, "$#,##0.00")
Debug.Print "Item 3", Format(10000, "$#,##0.00")
End Sub</code></pre>
<h3 id="format-elapsed-time">Format Elapsed Time</h3>
<pre><code class="language-vbnet">Function FormatElapsedTime(seconds As Long) As String
Dim hours As Long
Dim minutes As Long
Dim secs As Long
hours = seconds \ 3600
minutes = (seconds Mod 3600) \ 60
secs = seconds Mod 60
FormatElapsedTime = Format(hours, "00") & ":" & _
Format(minutes, "00") & ":" & _
Format(secs, "00")
End Function
' Usage
Debug.Print FormatElapsedTime(3661) ' 01:01:01</code></pre>
<h3 id="scientific-notation">Scientific Notation</h3>
<pre><code class="language-vbnet">Function FormatScientific(value As Double, decimals As Integer) As String
Dim formatStr As String
formatStr = "0." & String(decimals, "0") & "E+00"
FormatScientific = Format(value, formatStr)
End Function
' Usage
Debug.Print FormatScientific(1234567, 2) ' 1.23E+06</code></pre>
<h3 id="conditional-formatting">Conditional Formatting</h3>
<pre><code class="language-vbnet">Function FormatNumber(value As Double) As String
' Format: positive;negative;zero;null
FormatNumber = Format(value, "$#,##0.00;($#,##0.00);-;N/A")
End Function
' Usage
Debug.Print FormatNumber(1234.5) ' $1,234.50
Debug.Print FormatNumber(-500) ' ($500.00)
Debug.Print FormatNumber(0) ' -</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="multi-section-format-strings">Multi-Section Format Strings</h3>
<pre><code class="language-vbnet">' Format: positive;negative;zero;null
Function FormatWithSigns(value As Variant) As String
If IsNull(value) Then
FormatWithSigns = "N/A"
Else
FormatWithSigns = Format(value, "+#,##0.00;-#,##0.00;Zero")
End If
End Function
' Color-coded text (for display in rich text)
Function FormatColorCoded(value As Double) As String
' Positive=green, Negative=red, Zero=black
If value > 0 Then
FormatColorCoded = "[Green]" & Format(value, "$#,##0.00")
ElseIf value < 0 Then
FormatColorCoded = "[Red]" & Format(value, "($#,##0.00)")
Else
FormatColorCoded = "[Black]$0.00"
End If
End Function</code></pre>
<h3 id="invoice-number-formatting">Invoice Number Formatting</h3>
<pre><code class="language-vbnet">Function FormatInvoiceNumber(invoiceNum As Long, prefix As String) As String
FormatInvoiceNumber = prefix & "-" & Format(invoiceNum, "000000")
End Function
' Usage
Debug.Print FormatInvoiceNumber(123, "INV") ' INV-000123
Debug.Print FormatInvoiceNumber(45678, "PO") ' PO-045678</code></pre>
<h3 id="custom-number-format-builder">Custom Number Format Builder</h3>
<pre><code class="language-vbnet">Function BuildNumberFormat(decimals As Integer, _
Optional useSeparator As Boolean = True, _
Optional prefix As String = "", _
Optional suffix As String = "") As String
Dim formatStr As String
' Build integer part
If useSeparator Then
formatStr = "#,##0"
Else
formatStr = "0"
End If
' Add decimal part
If decimals > 0 Then
formatStr = formatStr & "." & String(decimals, "0")
End If
' Add prefix/suffix
formatStr = prefix & formatStr & suffix
BuildNumberFormat = formatStr
End Function
' Usage
Debug.Print Format(1234.5, BuildNumberFormat(2, True, "$", "")) ' $1,234.50</code></pre>
<h3 id="format-for-sql-queries">Format for SQL Queries</h3>
<pre><code class="language-vbnet">Function FormatForSQL(value As Variant) As String
Select Case VarType(value)
Case vbString
' Escape single quotes
FormatForSQL = "'" & Replace(CStr(value), "'", "''") & "'"
Case vbDate
' Format as ISO date
FormatForSQL = "'" & Format(value, "yyyy-mm-dd hh:nn:ss") & "'"
Case vbNull
FormatForSQL = "NULL"
Case vbBoolean
If CBool(value) Then
FormatForSQL = "1"
Else
FormatForSQL = "0"
End If
Case Else
FormatForSQL = CStr(value)
End Select
End Function</code></pre>
<h3 id="dynamic-column-width-formatting">Dynamic Column Width Formatting</h3>
<pre><code class="language-vbnet">Function FormatColumn(value As Variant, width As Integer, _
Optional align As String = "left") As String
Dim formatted As String
formatted = CStr(value)
If Len(formatted) > width Then
formatted = Left(formatted, width - 3) & "..."
Else
Select Case LCase(align)
Case "right"
formatted = Space(width - Len(formatted)) & formatted
Case "center"
Dim leftPad As Integer
leftPad = (width - Len(formatted)) \ 2
formatted = Space(leftPad) & formatted & _
Space(width - Len(formatted) - leftPad)
Case Else ' left
formatted = formatted & Space(width - Len(formatted))
End Select
End If
FormatColumn = formatted
End Function</code></pre>
<h3 id="localized-datetime-formatting">Localized Date/Time Formatting</h3>
<pre><code class="language-vbnet">Function FormatLocalizedDate(dt As Date, style As String) As String
' Uses system locale settings
Select Case LCase(style)
Case "short"
FormatLocalizedDate = Format(dt, "Short Date")
Case "long"
FormatLocalizedDate = Format(dt, "Long Date")
Case "iso"
FormatLocalizedDate = Format(dt, "yyyy-mm-dd")
Case "filename"
' Safe for filenames
FormatLocalizedDate = Format(dt, "yyyy-mm-dd_hhnnss")
Case Else
FormatLocalizedDate = Format(dt, "General Date")
End Select
End Function</code></pre>
<h2 id="error-handling">Error Handling</h2>
<pre><code class="language-vbnet">Function SafeFormat(value As Variant, formatStr As String) As String
On Error GoTo ErrorHandler
If IsNull(value) Then
SafeFormat = ""
Else
SafeFormat = Format(value, formatStr)
End If
Exit Function
ErrorHandler:
Select Case Err.Number
Case 13 ' Type mismatch
Debug.Print "Format error: Invalid data type for format string"
SafeFormat = CStr(value)
Case 5 ' Invalid procedure call
Debug.Print "Format error: Invalid format string"
SafeFormat = CStr(value)
Case Else
Debug.Print "Format error " & Err.Number & ": " & Err.Description
SafeFormat = ""
End Select
End Function</code></pre>
<h3 id="common-errors">Common Errors</h3>
<ul>
<li><strong>Error 13</strong> (Type Mismatch): Value type incompatible with format string</li>
<li><strong>Error 5</strong> (Invalid procedure call): Invalid format string syntax</li>
<li><strong>Error 6</strong> (Overflow): Value too large for format</li>
</ul>
<h2 id="performance-considerations">Performance Considerations</h2>
<ul>
<li>Format is relatively fast for simple conversions</li>
<li>Complex format strings take longer to parse</li>
<li>Avoid calling Format in tight loops if possible</li>
<li>Consider caching format strings used repeatedly</li>
<li>String concatenation with Format can be slow</li>
<li>For simple conversions, CStr/Str may be faster</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<h3 id="use-named-formats-when-possible">Use Named Formats When Possible</h3>
<pre><code class="language-vbnet">' Good - Clear and locale-aware
formatted = Format(amount, "Currency")
' Less portable - Hard-coded currency symbol
formatted = Format(amount, "$#,##0.00")</code></pre>
<h3 id="store-format-strings-as-constants">Store Format Strings as Constants</h3>
<pre><code class="language-vbnet">Const FMT_CURRENCY = "$#,##0.00"
Const FMT_PERCENT = "0.00%"
Const FMT_DATE_ISO = "yyyy-mm-dd"
formatted = Format(value, FMT_CURRENCY)</code></pre>
<h3 id="handle-null-values">Handle Null Values</h3>
<pre><code class="language-vbnet">' Good - Check for Null
If Not IsNull(value) Then
formatted = Format(value, "0.00")
Else
formatted = "N/A"
End If</code></pre>
<h2 id="comparison-with-other-functions">Comparison with Other Functions</h2>
<h3 id="format-vs-formatnumber"><code>Format</code> vs <code>FormatNumber</code></h3>
<pre><code class="language-vbnet">' Format - More flexible, custom formats
result = Format(1234.567, "#,##0.00")
' FormatNumber - Simpler, fewer options
result = FormatNumber(1234.567, 2)</code></pre>
<h3 id="format-vs-formatcurrency"><code>Format</code> vs <code>FormatCurrency</code></h3>
<pre><code class="language-vbnet">' Format - Custom currency format
result = Format(1234.56, "$#,##0.00")
' FormatCurrency - Uses system locale
result = FormatCurrency(1234.56)</code></pre>
<h3 id="format-vs-formatdatetime"><code>Format</code> vs <code>FormatDateTime</code></h3>
<pre><code class="language-vbnet">' Format - Custom date format
result = Format(Now, "yyyy-mm-dd hh:nn:ss")
' FormatDateTime - Named formats only
result = FormatDateTime(Now, vbShortDate)</code></pre>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Format strings are not validated until runtime</li>
<li>Limited regex or pattern matching capabilities</li>
<li>Cannot format arrays or objects directly</li>
<li>No built-in support for custom cultures</li>
<li>Some format characters are locale-dependent</li>
<li>Return value is always <code>String</code> (<code>Variant</code>)</li>
</ul>
<h2 id="format-string-reference">Format String Reference</h2>
<h3 id="numeric-format-characters">Numeric Format Characters</h3>
<ul>
<li><strong>0</strong>: Digit placeholder (displays 0 if no digit)</li>
<li><strong>#</strong>: Digit placeholder (displays nothing if no digit)</li>
<li><strong>.</strong>: Decimal placeholder</li>
<li><strong>,</strong>: Thousand separator</li>
<li><strong>%</strong>: Percentage placeholder (multiplies by 100)</li>
<li><strong>E+</strong>, <strong>E-</strong>, <strong>e+</strong>, <strong>e-</strong>: Scientific notation</li>
</ul>
<h3 id="datetime-format-characters">Date/Time Format Characters</h3>
<ul>
<li><strong>d</strong>, <strong>dd</strong>: Day (1-31, 01-31)</li>
<li><strong>ddd</strong>, <strong>dddd</strong>: Day name (Mon, Monday)</li>
<li><strong>m</strong>, <strong>mm</strong>: Month (1-12, 01-12)</li>
<li><strong>mmm</strong>, <strong>mmmm</strong>: Month name (Jan, January)</li>
<li><strong>yy</strong>, <strong>yyyy</strong>: Year (25, 2025)</li>
<li><strong>h</strong>, <strong>hh</strong>: Hour (0-23, 00-23)</li>
<li><strong>n</strong>, <strong>nn</strong>: Minute (0-59, 00-59)</li>
<li><strong>s</strong>, <strong>ss</strong>: Second (0-59, 00-59)</li>
<li><strong>AM/PM</strong>, <strong>am/pm</strong>: 12-hour time indicator</li>
</ul>
<h2 id="related-functions">Related Functions</h2>
<ul>
<li><code>FormatNumber</code>: Formats a number with specified decimal places</li>
<li><code>FormatCurrency</code>: Formats a number as currency</li>
<li><code>FormatPercent</code>: Formats a number as percentage</li>
<li><code>FormatDateTime</code>: Formats a date/time value</li>
<li><code>Str</code>: Converts number to string</li>
<li><code>CStr</code>: Converts expression to string</li>
</ul>
</article>
<div style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border-color);">
<p>
<a href="index.html">← Back to String</a> |
<a href="../index.html">View all functions</a>
</p>
</div>
</main>
<footer>
<div class="container">
<p>© 2024-2026 VB6Parse Contributors. Licensed under the MIT License.</p>
</div>
</footer>
</body>
</html>