首页 > 解决方案 > 如何修复 hh:mm 格式

问题描述

我有一个从特定信息系统导入的 Excel 文件。我一直在通过 VBA 代码实现它的自动化。但是我在处理 hh:mm 单元格时遇到了问题。我无法总结它们,我尝试将它们格式化为 hh:mm,我还尝试将输出单元格格式化为 [HH]:MM,但似乎都不起作用。

我想问题在于单元格的格式,它们在 Times New Roman 中,看起来有点不对劲。我需要一个 vba 代码来选择某个范围并复制旧值并再次粘贴它们,但使用正常的默认 Excel 格式。

在此处输入图像描述

标签: excelvbadatetime

解决方案


您将必须自定义格式要汇总的单元格[h]:mm

如果源单元格中的时间不正确或被格式化为文本,这可能不起作用。您可以手动将单元格格式化为General,然后按F2然后Enter键检查它是否有效。

在您自动执行此操作之前,您需要了解我们在做什么。

  1. 更改格式
  2. 更改Formula单元格的而不是Value. 然而,在这种情况下,两者是相同的。

我怎样才能使这个过程自动化,我不能手动对数千个细胞执行此操作.. – Yassine Lachgar 2 分钟前

试试这个

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lastRow As Long, lastCol As Long
    Dim rng As Range, aCell As Range

    '~~> Set this to the relevant worksheet
    Set ws = Sheet1

    With ws
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            '~~> Find Last row and last column
            lastRow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row

            lastCol = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByColumns, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Column

            '~~> Identify your range
            Set rng = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))

            '~~> Set the format. Be careful with this
            '~~> This will overwrite existing formats
            rng.NumberFormat = "General"

            '~~> Perform F2 + Enter via code
            For Each aCell In rng
                aCell.Formula = aCell.Value
            Next aCell
        End If
    End With
End Sub

推荐阅读