插入 Excel 单元格时的 VBA 日期值会更改其格式

Cod*_*odo 0 excel vba excel-2010

我的日期变量格式如下:25_December_2010

一旦我使用

Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate,"_"," ")
MsgBox strDate
Run Code Online (Sandbox Code Playgroud)

肯定会MsgBox弹出一个窗口并显示:2010 年 12 月 25 日。

但是,一旦我尝试将值放入单元格中,例如:

Sheets("Sheet1").Range("A1").Value = strdate
Run Code Online (Sandbox Code Playgroud)

而不是用以下cell内容填充:25 December 2010; Excel 会自行操作并使用令人烦恼的条目配置填充单元格:25-Dec-2010

如何让我的单元格填充hyphen中间没有字符并且不修剪月份名称?

Ron*_*eld 5

此代码以您想要的格式将日期放入 A1 中:

Option Explicit
Sub WriteDate()
    Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate, "_", " ")
MsgBox strDate

With Sheets("Sheet1").Range("A1")
    .Value = strDate
    .NumberFormat = "dd mmmm yyyy"
End With

End Sub
Run Code Online (Sandbox Code Playgroud)

我不确定是否有必要,但为了清楚起见,由于 strDate 是字符串数据类型,我可能会使用

.Value = CDate(strDate)
Run Code Online (Sandbox Code Playgroud)

在将其写入工作表之前,将其显式转换为日期数据类型可能在非英语版本中有价值,但我没有具体检查过。