Module
Contents
Index 🔎︎

# FormatDateTime Function [VBA]

Applies a date and/or time format to a date expression and returns the result as a string.

该功能或常量可通过以下语句启用：Option VBASupport 1，该语句需要放置在模块的每个可执行程序代码的前面。

## 语法：

    FormatDateTime (DateExpression as Date [, NamedFormat as Integer])

## 返回值：

String

## 参数：

DateExpression: The date expression to be formatted.

NamedFormat: An optional vbDateTimeFormat enumeration specifying the format that is to be applied to the date and time expression. If omitted, the value vbGeneralDate is used.

### Date and Time formats (vbDateTimeFormat enumeration)

Named Constant | Value | Description
vbGeneralDate | 0 | Displays a date and/or time as defined in your system's General Date setting. If a date only, no time is displayed; If a time only, no date is displayed.
vbLongDate | 1 | Display a date using the long date format specified in your computer's regional settings.
vbShortDate | 2 | Display a date using the short date format specified in your computer's regional settings.
vbLongTime | 3 | Displays a time as defined in your system's Long Time settings.
vbShortTime | 4 | Display a time using the 24-hour format (hh:mm).

## 错误代码：

13 数据类型不匹配

## 示例：

    REM  *****  BASIC  *****

    Option VBASupport 1

    Sub DateFormat

     Dim d as Date

     d = ("1958-01-29 00:25")

     msgbox("General date format : " & FormatDateTime(d))

     msgbox("Long date format : " & FormatDateTime(d,vbLongDate))

     msgbox("Short date format : " & FormatDateTime(d,vbShortDate))

     msgbox("Long time format : " & FormatDateTime(d,3))

     msgbox("Short time format : " & FormatDateTime(d,vbShortTime))

    End Sub

相关主题

VBA 时期与时间函数