【问题标题】:VBA: transform date to dd/mm/yyyyVBA:将日期转换为 dd/mm/yyyy
【发布时间】:2023-02-22 18:50:35
【问题描述】:

我对 VBA 很陌生,我有一张工作表,其中 E 列中的日期格式如下:

Date
20230118
20220227

我想编写一个代码将其转换为 dd/mm/yyyy 格式。我尝试使用工作表函数 LEFT()、RIGHT() 和 MID() 来分隔日、月和年。但是我不确定如何使用这些在该列中的每个单元格的完全相同的列中创建我想要的格式。我该怎么做呢?

【问题讨论】:

  • 你确定吗它的格式为Date而不是文本或数字?请检查并澄清问题...
  • 它的格式为自定义,而不是日期。那就是问题所在
  • 定制的,定制的,但它可能是一个定制的Date...它是格式化为文本,还是数字?
  • @FaneDuru 一个自定义号码:########

标签: excel vba


【解决方案1】:

尝试这个

Sub Change_Date_Format()

   Activeworkbook.Sheets("Sheet1").Columns("E:E").NumberFormat = "dd/mm/yyyy"

End Sub

【讨论】:

    【解决方案2】:

    请使用下一个功能:

    Function makeDate_(strD) As Date
        Dim d As Date
        d = DateSerial(left(strD, 4), Mid(strD, 5, 2), Right(strD, 2))
        makeDate_ = Format(d, "dd/mm/yyyy")
    End Function
    

    它可以被测试为:

    Sub testMakeDate()
     Dim x As String, y As Long
     x = "20230118"
     y = 20220227
    
      Debug.Print makeDate_(x)
      Debug.Print makeDate_(y)
    End Sub
    

    该值可以是数字或字符串。该函数可以用作 UDF(用户定义函数)并作为公式调用:

      =makeDate_(A2)
    

    或者更快,将要处理的范围放在一个数组中,在代码末尾返回处理结果:

    Sub testMakeDate_()
      Dim sh As Worksheet, lastR As Long, rng As Range, arr, i As Long
      
      Set sh = ActiveSheet
      lastR = sh.Range("A" & sh.rows.count).End(xlUp).Row 'the column where the custom Date/number to be processed
      
      Set rng = sh.Range("A2:A" & lastR)
      arr = rng.Value
      
      For i = 1 To UBound(arr)
         arr(i, 1) = makeDate_(arr(i, 1))
      Next i
      With rng
            .NumberFormat = "dd/mm/yyyy"
            .Value = arr
      End With
    End Sub
    

    如果您的数据不在 A:A 中,请使用您的真实列标题调整两条代码行 lastR = sh.Range("A" & sh....Set rng = sh.Range("A2:A" & lastR)...

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 2020-06-22
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多