使用VBA获取正确的日期 [英] Obtaining the correct date using VBA

查看:54
本文介绍了使用VBA获取正确的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2018年1月2日下午12:25:00

01/02/2018 12:25:00 PM

我有上述日期,该日期在Excel电子表格的B1单元格中.日期是2018年2月1日,但下面的VBA代码

I have the above date which is in an Excel spreadsheet's B1 cell. The date is 01 February 2018 but the VBA code below

thedate = CDate(Application.Cells(linecount, 2))

将其转换为2018年1月2日

converts this to 02 January 2018

我要使用什么VBA代码来保留此日期2018年2月1日?

What VBA code do I use to have this remain 01 February 2018?

推荐答案

如果要使用VBA返回字符串的 Date 数据类型值 01/02/2018 12:25:00 PM 代表您当地的区域日期设置中的 2018年2月1日(在消息框中),您可以使用:

If you want to use VBA to return a Date data type value of string 01/02/2018 12:25:00 PM representing 01 February 2018 in your local regional date settings (in a message box), you could use:

Dim dt as String
dt = "01/02/2018 12:25:00 PM"
MsgBox DateSerial(Mid(dt, 7, 4), Mid(dt, 4, 2), Left(dt, 2))

这是的显示方式.参见下面的注释.

This is how it displays for me. See note below.

如果您实际上希望以您提到的特定格式"dd MMMM yyyy" 返回字符串(在消息框中),则可以使用:

If you actually want a string to be returned (in a messages box) in the specific format you mentioned, "dd MMMM yyyy", you could use:

Dim dt as String
dt = "01/02/2018 12:25:00 PM"
MsgBox Format(DateSerial(Mid(dt, 7, 4), Mid(dt, 4, 2), Left(dt, 2)), "dd MMMM yyyy")

如果您要存储此数据(包括时间),或将其用于计算,请使用正确的 方法会更像:

If you wanted to store this data (including the time), or use it for calculations, then the proper way to do it would be more like:

Dim strMyDate as String, dtMyDate as Date
strMyDate = "01/02/2018 12:25:00 PM"
dtMyDate = DateSerial(Mid(strMyDate, 7, 4), Mid(strMyDate, 4, 2), _
    Left(strMyDate, 2)) + TimeValue(Mid(strMyDate, 11))
MsgBox dtMyDate

请注意,这些MsgBox是根据 my 系统的Windows设置(如下所示)显示日期/时间的,此处显示了它们如果需要,可以进行调整.(因此,上面的结果对您来说将有所不同.)

Note that these MsgBox's are displaying date/time's based on my system's Windows settings (shown below), shown here, where they could be adjusted if required. (Hence, the results above will appear differently for you.)

  • 通过点击 类型地区,然后点击ᴇɴᴛᴇʀ.

(点击放大)

DateTime实际上以数字形式存储在Excel中,其中 0 = 1899年12月30日 +1 = +1天,因此您的示例日期 2018年2月1日下午12:25:00 实际上只是DateTime序列号的格式化格式,在本例中为 43132.5173611 .

The DateTime is actually stored in Excel as a number where 0 = December 30, 1899 and +1 = +1 day, so your example date of 01 February 2018 12:25:00 PM is actually only a formatted representation of the DateTime serial number, in this case, 43132.5173611.

MSDN:

MSDN : Format function (VBA)

MSDN: TimeValue函数(VBA)

MSDN : TimeValue function (VBA)

Microsoft.com: 如何在Excel中使用日期和时间

Microsoft.com : How to use dates and times in Excel

这篇关于使用VBA获取正确的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆