Home » excel » excel – How to fix hh:mm format

excel – How to fix hh:mm format

Posted by: admin May 14, 2020 Leave a comment


I have an Excel file imported from a specific information system. I have been working with its automation through VBA code. However i encountered a problem while dealing with hh:mm cells. I can’t sum them up, I tried formatting them to hh:mm, I also tried to format my output cell as [HH]:MM, none of it seems to work.

I guess the problem is with how the cells are formatted, they are in Times New Roman and seem a bit off.
I need a vba code to select a certain range and copy the ancien value and paste them again, but with the normal default Excel formatting.

enter image description here

How to&Answers:

You will have to custom format the cell where you are summing to [h]:mm

This may not work if the time is not correct in the source cells or are formatted as Text. You can manually format the cells as General and then press F2 and then Enter key to check if it works.

Before you automate this, you need to understand what we are doing.

  1. Changing the format
  2. Changing the Formula of the cell and not the Value. In this case, however both are the same.

how can I automate this process, I cant do this manually to thousands of cells.. – Yassine Lachgar 2 mins ago

Try this

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, _

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

            '~~> 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