【问题标题】:How can I bring correct date format in VBA?如何在 VBA 中引入正确的日期格式?
【发布时间】:2021-06-06 14:38:42
【问题描述】:

所以,我正在尝试自动化 VBA 中的一些日期。我分别获得日期、月份和年份,并将所有三个连接到 VBA 中的一个单元格中。但是通过这种方法,我得到了“未格式化”的日期,并且无法在几个月内过滤它们。 Excel 将它们视为“文本”

在附加的屏幕截图中,您可以看到底部 4 个单元格,我实际上是通过按 F2 并输入来刷新的。这会将它们更新为日期格式,并且过滤器将它们视为“日期”

如何实现自动化,以便仅在 VBA 中以这种格式放置它们?

代码如下

    'for each row run a formula to concatenate G+F+H for DD/MM/YYYY
    For Cnt = 2 To Cnt2
    
        If Cells(Cnt, 7).Value > 12 Then
            Cells(Cnt, 9).Value = Cells(Cnt, 7).Value & "." & Cells(Cnt, 6).Value & "." & Cells(Cnt, 8).Value
        Else
            Cells(Cnt, 9).Value = Cells(Cnt, 6).Value & "." & Cells(Cnt, 7).Value & "." & Cells(Cnt, 8).Value
            
        End If
            
    Next Cnt
    
    'delete F G H columns
    Columns("F:H").Select
    Selection.EntireColumn.Delete
    
    Columns("F:F").Select
    Selection.NumberFormat = "d/m/yy"

【问题讨论】:

  • 创建“真实”日期,然后对其进行格式化。使用 vba Dateserial 函数来做到这一点。

标签: excel vba date format


【解决方案1】:

尝试使用此代码,请根据需要配置所有内容

祝你好运

'Copy all code
'This is the configurable part
    Private Const _
    MyFormat = "dd.mm.yyyy", _
    MySheet = "Test", _
    MyFirstRangeCell = "F1"
'This is the configurable part

   'This dont need move anything
Function MyFormatDay(d_ As String, m_ As String, y_ As String) As String
    MyFormatDay = Format(DateSerial(y_, m_, d_), MyFormat)
End Function

'this dont need to move so much, maybe nothing
Sub GetDates()
    Sheets(MySheet).Select
    Range(MyFirstRangeCell).Select
    Do While ActiveCell <> ""
    ActiveCell.Offset(0, 3) = MyFormatDay(ActiveCell, ActiveCell.Offset(0, 1),    ActiveCell.Offset(0, 2))
    ActiveCell.Offset(1, 0).Select
    Loop


End Sub


'Copy all code

【讨论】:

  • 你奇怪的参数x_应该被声明为整数。
【解决方案2】:

使用DateSerial 而不是串联:

Cells(Cnt, 9).Value = DateSerial(Cells(Cnt, 8).Value, Cells(Cnt, 6).Value, Cells(Cnt, 7).Value)

【讨论】:

  • 这已经解决了我的问题没有和类似的声明:) 非常感谢 BigBen
猜你喜欢
  • 1970-01-01
  • 2016-11-17
  • 2012-07-02
  • 1970-01-01
  • 2019-12-12
  • 2014-06-28
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
相关资源
最近更新 更多