2013-07-18 139 views
1

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

主要是我想知道的是,如果这是可能的,或者我应该尝试替代编码来分开他们开始。提前致谢!

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 
+0

这是否需要通过宏?你可以使用公式和设置的组合吗? – PowerUser

回答

2

您可以使用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 "00:05" 
    ' Sets the date in the cell of the first column 
    Cells(x,1).Value = Format(dTime, "mm/dd/yyyy") 

    ' Sets the time in the cell of the second column 
    Cells(x,2).Value = Format(dTime, "hh:mm:ss AM/PM") 
    x = x + 1 
Next dTime 
End Sub 
+1

我想你应该把最后一个答案的一部分加入到这个中。避免选择/激活任何东西。你的答案在这里起作用,但是可以很容易地避免选择单元并写入活动单元。 –

+0

100%正确@餐饮部门负责人..我很忙,只是更新了OP的代码。 – Jaycal

+0

+1。很好的答案,尤其是编辑。 ;-) –