【发布时间】:2022-01-16 11:06:04
【问题描述】:
我的工作表有这些公式。 T 列中的一些值是日期,一些是字符串或一般值:
及其价值观:
我有这个VBA 代码循环遍历列中的每个单元格并将字符串值转换为日期并格式化日期。但是,对于两位数的月份和日期,它工作得非常好,但不是个位数。问题的原因是什么,我怎样才能让它总是导致两位数,即“01 - 02 -2021”,不是“1/2/2021”?
Sub Date_format()
Dim Cel As Range
Dim i As Integer
i = ActiveWorkbook.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
' First I applied mm - dd as the same as the work sheet
ActiveSheet.Range("T2:T" & i).NumberFormat = "mm-dd-yyyy"
For Each Cel In ActiveSheet.Range("T2:T" & i)
If Not Cel.Value = "n/a" Then
' Then I applied dd - mm to swap the day and month
Cel.Value = Format(DateValue(Cel.Value), "dd - mm - yyyy")
End If
Next
End Sub
一旦我将.NumberFormat = "dd-mm-yyyy" 应用于该范围,我的另一个计算天数的公式=DAYS(TODAY(),T2) 将不再适用于大多数单元格,如下图所示:
【问题讨论】:
-
在 FOR 循环前添加
.Range("T2:T" & i).NumberFormat = "dd - mm - yyyy" -
once I applied .NumberFormat = "mm-dd-yyyy" to the range my other formula =DAYS(TODAY(),T2) that calculate days are not working anymore on some cells哪些单元格? -
您提到您已申请
.NumberFormat = "mm-dd-yyyy"但T5 显示“dd-mm-yyyy”?您还可以使用您正在使用的当前代码更新问题吗? -
@SiddharthRout 首先我申请了
mm - dd与工作表相同。然后我重新申请dd - mm来交换日期和月份。我认为问题出在日期格式上? -
将
Cel.Value = Format(DateValue(Cel.Value), "dd - mm - yyyy")更改为Cel.Value =DateValue(Cel.Value)。您已经应用了格式。无需在循环中应用它。