从文本格式到日期格式的日期转换部分工作
我想将日期从文本格式转换为日期格式。我在下面提供的代码适用于所有具有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
说实话,这有点难以理解你的代码 - 你在某种程度上处理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
完美!工作!谢谢!还有一个问题是否可能。我想在另一张表中查找此日期,但另一张表中的日期格式为“dd/mm/yyyy hh:mm”。是否有可能仍然忽视hh:mm? –
嗯,棘手,取决于确切的条件。也许,如果你可以用'= int(A2)'这样的公式(删除时间部分)在另一张表中添加一个帮手列表 – FunThomas
ok!我会尝试!上面粘贴的代码只是最后一件事......它对于特定的日期非常有用,但我之前忘记提到代码每次应该转换的日期是用户的输入形式,它保存为名为myValue的变量因此,我试图添加这个变量而不是Sheets(“1”)。Range(“B1”)。Value,但不会工作,因为myValue是一个变量的二倍。无论如何,我编辑了代码,以防万一你能帮忙! –
请考证'With'命令做什么。你以绝对不正确的方式使用它,它将在未来让你陷入麻烦。 – jsotola