Obtaining the correct date using VBA

时间秒杀一切 提交于 2021-01-28 08:15:24

问题


01/02/2018 12:25:00 PM

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))

converts this to 02 January 2018

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


回答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.

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


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.)

  • Open these settings by hitting Windows Key type region, and hit ᴇɴᴛᴇʀ.

    (Click to enlarge)

  • 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.


More Information:

  • MSDN : DateSerial function (VBA)

  • MSDN : Format function (VBA)

  • MSDN : TimeValue function (VBA)

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



来源:https://stackoverflow.com/questions/50289586/obtaining-the-correct-date-using-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!