簡體   English   中英

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

[英]Format column with date to specific format - 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

我認為您發布的代碼沒有任何問題,所以我不確定您要執行的操作或當前工作失敗的地方,但是您不需要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

您無法真正使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM