简体   繁体   English

VBA Excel 将日期时间转换为文本

[英]VBA Excel Convert Date Time to Text

I'd like to convert a date time to text.我想将日期时间转换为文本。

Example: 10/22/2019 2:10 PM should be converted to 43760.59028.示例:10/22/2019 2:10 PM 应转换为 43760.59028。 I know how to do this if I was trying to convert a cell in a spreadsheet, but I'm trying to convert a date time variable.如果我试图转换电子表格中的单元格,我知道如何执行此操作,但我正在尝试转换日期时间变量。

I've tried: vdate = Format(CDate("10/22/2019 2:10 PM"), "@")我试过: vdate = Format(CDate("10/22/2019 2:10 PM"), "@")

I end up with a string rather than the text conversion to a number.我最终得到一个字符串,而不是文本转换为数字。

How do I convert a date or date time and store the value in a variable?如何转换日期或日期时间并将值存储在变量中?

Format yields a String , you don't want that. Format产生一个String ,你不希望这样。

Declare vdate as a Double : vdate声明为Double

Dim vdate As Double

Now this will work:现在这将起作用:

vdate = CDate("10/22/2019 2:10 PM")

...but that's an implicit type conversion from Date to Double ; ...但这是从DateDouble的隐式类型转换; you can make it explicit:你可以明确表示:

vdate = CDbl(CDate("10/22/2019 2:10 PM"))

...as Scott mentioned in the comments ...正如斯科特在评论中提到的

this example may be help you这个例子可能对你有帮助

Sub convert_date2txt()
     Dim theRange as Range
     Set theRange = Selection
     Dim sDate As String
     For Each theCell In theRange
         sDate=Format(theCell,"dd/mm/yyyy")
         theCell.Value = sDate
         theCell.NumberFormat="@"
     Next
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM