我正在尝试将日期从文本格式转换为日期格式。我在下面提供的代码适用于dd数大于12的所有日期。因此,对于dd = 13到dd = 31,它可以正常工作。当我有一个dd< 13的日期时,它就不起作用了。我在下面提供的日期是代码不能工作的日期的示例。它将单元格B1留空。此外,我的系统设置设置为dd / mm / yyyy,因此系统可以正常使用。有谁知道为什么它不起作用?
Sheets("1").Select
Dim myValue As Variant
myValue = InputBox("Simi, type the date of the shipments that you want to create the report for", "Date", 1)
Sheets("1").Range("B1").Value = myValue
With Sheets("1").Range("B1")
Dim t() As String
t = Split(myValue, "/") ' Split into pieces
If UBound(t) = 2 Then ' If 3 elements found:
myValue = DateSerial(t(2), t(1), t(0)) ' Convert to Date
End If
End With
答案 0 :(得分:1)
说实话,你有点难以理解你的代码 - 你在某种程度上处理VBA中的Excel公式 - 不需要那样。
尝试类似
的内容 Dim r As Range
Set r = ThisWorkbook.Sheets(1).Range("B1")
r.Value = "08/01/2017"
With r
Dim s As String, t() As String
s = r.Value ' Read cell content into string
t = Split(s, "/") ' Split into pieces
If UBound(t) = 2 Then ' If 3 elements found:
r.Value = DateSerial(t(2), t(1), t(0)) ' Convert to Date
End If
End With
带有用户输入的版本(在转换之前无需将其写入单元格)
Dim myValue As Variant
myValue = InputBox("Simi, type the date of the shipments that you want to create the report for", "Date", 1)
Dim r As Range
Set r = ThisWorkbook.Sheets(1).Range("B1")
With r
Dim s As String, t() As String
s = myValue ' Use user input
t = Split(s, "/") ' Split into pieces
If UBound(t) = 2 Then ' If 3 elements found:
r.Value = DateSerial(t(2), t(1), t(0)) ' Convert to Date
End If
End With