vba 将日期/时间拆分为 2 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17731795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:19:27  来源:igfitidea点击:

Splitting Date/Time into 2 columns

excelvba

提问by mnp

I currently have code that outputs the date and time into column A, but I would like for them to be separate (Date in column A, Time in Column B). I tried to figure this out with recording a macro and doing the delimiting process within Excel, but it didn't work like I wanted.

我目前有将日期和时间输出到 A 列的代码,但我希望它们是分开的(A 列中的日期,B 列中的时间)。我试图通过录制宏并在 Excel 中进行分隔过程来解决这个问题,但它并没有像我想要的那样工作。

Mainly what I want to know is if this is possible, or I should try alternative coding to separate them to begin with?

我主要想知道这是否可行,或者我应该尝试替代编码来将它们分开?

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

回答by Jaycal

You can use Format(Expression,[format])to format the values before putting it in the cell. See the updated code below (feel free to update the formats as you see fit)

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