2013-12-17 61 views
0

我正在写一个excel vba宏。格式列与日期到特定格式 - Excel VBA

我有一个超过10,000行的大型工作表。 其中一列具有此格式的日期:10/28/13 06:57,单元格具有格式设置的常规编号。

我想格式化它只有四个数字的格式为:mmdd(1028上面的例子)

这里是我迄今为止在子程序:

' This subroutine formats the columns to what is necessary for output 
Sub formatColumns() 
    ' Set the LastRow variable to hold the last row number 
    lastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row 

    Dim cell As Range 

    For Each cell In Range("B3:B" & lastRow) 
     cell.NumberFormat = "mmdd;@" 
    Next 
End Sub 
+1

只需更换单元格的内容那么,你的满意是什么? – pnuts

+0

如果可以,请在内存中进行转换,而不是循环超过10 000个单元。如果格式是固定的,您应该能够从输入中提取所需的字符串。 – Trace

+0

问题是什么?您是否尝试应用格式化或者您是否将日期时间值转换为格式化的字符串? –

回答

3

你不能用那种mmdd数字格式真正格式化它。至少它不适合我。 (Excel 2010/Win 7 欧洲区域设置)

我建议它增加一个额外的列并复制数据以保留原始格式,最后隐藏该列。同时,您将使用Month()Day()函数来创建所需的格式。

Sub formatColumns() 
    Dim lastRow As Long 

    ' Set the LastRow variable to hold the last row number 
    lastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row 

    Dim cell As Range 
    For Each cell In Range("B3:B" & lastRow) 
     'cell.NumberFormat = "mmdd;@" 
     cell.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove 
     cell.Offset(0, -1).NumberFormat = "@" 
     cell.Offset(0, -1) = _ 
      IIf(Len(Month(cell)) = 1, "0" & Month(cell), Month(cell)) & _ 
      IIf(Len(Day(cell)) = 1, "0" & Day(cell), Day(cell)) 
    Next 

    Columns("C:C").EntireColumn.Hidden = True 
End Sub 

,如果你不希望添加一个额外的列,但你不介意失去原始格式那么你可以使用此代码

Sub formatColumns() 
    Dim lastRow As Long 

    ' Set the LastRow variable to hold the last row number 
    lastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row 

    Dim cell As Range 
    For Each cell In Range("B3:B" & lastRow) 
     'cell.NumberFormat = "mmdd;@" 
     cell = IIf(Len(Month(cell)) = 1, "0" & Month(cell), Month(cell)) & _ 
     IIf(Len(Day(cell)) = 1, "0" & Day(cell), Day(cell)) 
    Next 

End Sub 
+0

电子表格中隐藏的列会影响我尝试将其保存为不同格式的任何内容吗? – RXC

+0

@RXC,这是一个非常广泛的问题。这取决于格式。它会影响CSV中的结构,因为每行都会有一个额外的*列*。查看更新回答 – 2013-12-17 14:58:00

+1

谢谢,我宁愿不添加列,并且您的答案工作。 – RXC

5

我不要认为你发布的代码有什么问题,所以我不太清楚你正在尝试做什么或者你目前的工作失败,但是你不需要使用For/Next循环来做到这一点,你可以在整个范围内应用NumberFormat属性:

Sub formatColumns() 
    Dim lastRow as Long 
    ' Set the LastRow variable to hold the last row number 
    lastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row 

    Range("B3:B" & lastRow).NumberFormat = "mmdd" 

End Sub 
+0

我认为格式'mmdd'可能是问题 – 2013-12-17 14:53:23

+0

@mehow hmmmm这个数字格式适用于我,Win 7/Excel 2010. –

+1

Win7/Excel 2010 - 欧洲语言环境,它没有。 – 2013-12-17 15:02:58