将date的格式设置为特定的格式 – Excel VBA

我正在写一个excel vbamacros。

我有一个超过10,000行的大型工作表。 其中一列的date格式如下: 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 

你不能用这种mmdd数字格式真正格式化它。 至less它不适合我。 (Excel 2010 / Win 7 欧洲语言环境)

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

 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 

如果你不想添加额外的列,但你不介意丢失原始格式,那么你可以用这个代码来replace单元格的内容

 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 

我不认为你发布的代码有什么问题,所以我不太清楚你正在做什么或者你目前的工作在哪里,但是你不需要一个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