我目前有将日期和时间输出到A列的代码,但是我希望它们分开(A列中的日期,B列中的时间)。我试图通过记录宏并在Excel中进行定界处理来弄清楚这一点,但是它并没有达到我想要的效果。

我主要想知道的是这是否可行,还是我应该尝试使用其他编码将它们分开来?

Sub Macro1()

Dim dTime As Date
Range("A:A").Select
Selection.NumberFormat = "mm/dd/yyyy hh:mm:ss AM/PM"

Range("A1").Select
Set Cell = [A1]

For dTime = "3/01/2013 12:00:00 AM" To "3/02/2013 11:55:00 PM" Step "00:05"
ActiveCell.Value = dTime
ActiveCell.Offset(1, 0).Select

Next dTime

End Sub

最佳答案

您可以使用Format(Expression,[format])格式化值,然后再将其放入单元格中。请参阅下面的更新代码(可以随意更新格式)

Sub Macro1()

Dim dTime As Date
Dim x As Integer

x = 1

For dTime = "3/01/2013 12:00:00 AM" To "3/02/2013 11:55:00 PM" Step TimeValue("00:05:00")
    ' Sets the date in the cell of the first column
    Cells(x,1).Value = DateValue(dTime)

    ' Sets the time in the cell of the second column
    Cells(x,2).Value = TimeValue(dTime)

    ' Increment the row position
    x = x + 1
Next dTime
End Sub

10-05 21:22