簡體   English   中英

在VBA Excel中將日期字符串轉換為日期類型

[英]Converting a date string to date type in vba excel

我有一列日期從MS Project轉換為字符串形式的excel。 轉換后的格式類似於以下內容:“ 2014年3月31日,上午8:00”我想將“ 2014年3月31日,上午8:00”轉換為日期類型,但由於未格式化為MM-DD-YYYY不讓我。 有什么建議么?

例如,如果該值在單元格A2中,則可以執行以下操作:

= DATE(YEAR(A2),MONTH(A2),DAY(A2))

對於純VBA解決方案,請根據@cirrusone的建議進行擴展,請嘗試以下操作:

Public Sub lime()

  Dim dt As Date

  ' Convert the date string into a Date value.
  ' Assumes your date string is in cell A1 in the active worksheet of the active
  ' workbook.
  dt = CDate(Cells(1, 1))

  ' This will print the date with ".." as separators to show that it worked, i.e.
  ' it should be able to understand every part of the date string passed to it
  ' after having converted it to a Date value.
  MsgBox DatePart("d", dt) & ".." & DatePart("m", dt) & ".." & DatePart("yyyy", dt) & ".." & _
         DatePart("h", dt) & ".." & DatePart("n", dt) & ".." & DatePart("s", dt)

End Sub

我發表了一些評論來解釋它在做什么。 DatePart是提取日期位的有用函數(一般來說很有用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM