我的作業表有這個公式,T 列中的一些值是日期,一些是字串或一般值。 
及其價值觀 
我有這個代碼VBA,loop通過每個cell輸入column并將其轉換string value為 adate和format日期。但它是兩位數的作業完美的罰款month和day而不是單個數字。問題的原因是什么以及我如何使它始終產生兩位數,即“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 same as 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)計算天數的其他公式在大多數單元格上不再起作用,如圖所示
uj5u.com熱心網友回復:
請嘗試轉換這部分:
If Not Cel.Value = "n/a" Then
Cel.Value = Format(DateValue(Cel.Value), "dd - mm - yyyy")
End If
作為:
If Not Cel.Value = "n/a" Then
Cel.NumberFormat = "dd - mm - yyyy"
Cel.Value = Format(DateValue(Cel.Value), "dd - mm - yyyy")
End If
uj5u.com熱心網友回復:
正如我在上面的評論中提到的,添加
.Range("T2:T" & i).NumberFormat = "dd - mm - yyyy"
在FOR回圈之前。
這是在不使用回圈的情況下實作您想要的另一種方法。
代碼:
Option Explicit
Sub Date_format()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change this to the relevant sheet
Set ws = Sheet1
With ws
'~~> Last row in Col T
lRow = .Range("T" & .Rows.Count).End(xlUp).Row
With .Range("T2:T" & lRow)
.NumberFormat = "dd - mm - yyyy"
.Value = ws.Evaluate("index(IF(" & .Address & _
"<>""n/a"",DATEVALUE(" & .Address & "),""n/a""),)")
End With
End With
End Sub
截屏:

解釋:
這種方法使用EVALUATEwith INDEX, IFandDATEVALUE在不使用任何回圈的情況下進行轉換。有關其作業原理的說明,請參閱將整個范圍轉換為大寫而不遍歷所有單元格
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/380374.html
上一篇:確定單元格上/內是否有按鈕
