简体   繁体   English

使用 Excel VBA 将字符串格式化为具有两位数日期和月份的日期

[英]Format string to date with double digit day and month using Excel VBA

I have this code VBA that loop through each cell in column and convert the string value to a date and format the date.我有这个代码VBA loop遍历column中的每个cell并将string value转换为dateformat日期。 however it is working perfectly fine with double digit month and day but not single digit.但是,它在两位数的monthday上工作得非常好,但不是一位数。 what is cause of problem and how I can make it to always result in double digit ie "01 - 02 -2021" NOT "1/2/2021"什么是问题的原因以及如何使它始终导致两位数,即“01 - 02 -2021”而不是“2021 年 1 月 2 日”

Sub Date_format()
    
    Dim Cel As Range
    Dim i As Integer
    i = ActiveWorkbook.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
        
    For Each Cel In ActiveSheet.Range("T2:T" & i)
        If Not Cel.Value = "n/a" Then
            Cel.Value = Format(DateValue(Cel.Value), "dd - mm - yyyy")                
        End If
    Next
    
End Sub

Please, try transforming this part:请尝试转换这部分:

        If Not Cel.Value = "n/a" Then
            Cel.Value = Format(DateValue(Cel.Value), "dd - mm - yyyy")                
        End If

as:作为:

        If Not Cel.Value = "n/a" Then
            Cel.NumberFormat = "dd - mm - yyyy"
            Cel.Value = Format(DateValue(Cel.Value), "dd - mm - yyyy")                
        End If

As I mentioned in the comments above, add正如我在上面的评论中提到的,添加

.Range("T2:T" & i).NumberFormat = "dd - mm - yyyy" 

before the FOR loop.FOR循环之前。

Here is another way to achieve what you want without using loops.这是另一种在使用循环的情况下实现您想要的方法。

Code:代码:

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

Screenshot:截屏:

在此处输入图像描述

Explanation:解释:

This approach uses EVALUATE with INDEX , IF and DATEVALUE to do the conversion without using any loops.这种方法使用EVALUATEINDEXIFDATEVALUE来进行转换,而不使用任何循环。 For explanation on how it works, please see Convert an entire range to uppercase without looping through all the cells有关其工作原理的说明,请参阅将整个范围转换为大写而不循环遍历所有单元格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM