格式化日期为特定格式的列 - Excel VBA

时间:2013-12-17 14:39:50

标签: excel vba excel-vba formatting

我正在写一个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

2 个答案:

答案 0 :(得分:5)

我认为您发布的代码没有任何问题,所以我不太确定您要做的是什么,或者您当前的努力失败了,但您不需要{{1} }循环执行此操作,您可以将For/Next属性应用于整个范围:

NumberFormat

答案 1 :(得分: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
相关问题