Answered VBA Format() Function

  • Saturday, August 04, 2012 3:30 PM
    Moderator
     
     

    I am having a small problem with Format().  Consider:

    Sub TimeFormat()
    Dim t, st As String
    t = TimeSerial(25, 13, 11)
    With Range("A1")
        .Clear
        .NumberFormat = "[hh]:mm:ss"
        .Value = t
    End With
    st = Format(t, "[hh]:mm:ss")
    MsgBox st
    End Sub

    The value in A1 is correctly set to:

    25:13:11

    and the NumberFormat is also correctly set.

    However, the MsgBox displays:

    :12:11

    What is the problem and how do I fix it?


    gsnu201208

All Replies

  • Saturday, August 04, 2012 4:29 PM
     
     Answered Has Code

    Square brackets in a time format are valid in a cell format in Excel, but the Format function in VBA doesn't recognize them. Time formats in VBA are always clock time, there is no support for cumulative time.

    You can use

        st = Range("A1").Text
        MsgBox st

    to display the time as formatted in Excel.

    Regards, Hans Vogelaar

  • Saturday, August 04, 2012 4:46 PM
    Moderator
     
     
    Thanks!

    gsnu201208

  • Saturday, August 04, 2012 5:08 PM
     
     

    Wow!!  Hans, you really deserve that 'MVP' title!!

    Good stuff!!!!!


    Ryan Shuell

  • Monday, August 06, 2012 12:09 PM
    Moderator
     
     Answered

    Another way, without using a Cell

    Dim t As Date, st As String
    t = TimeSerial(25, 13, 11)
    st = Int(t * 24) & Format(t, ":nn:ss")
    MsgBox st

    Note nn not mm

    Peter Thornton

  • Monday, August 06, 2012 12:40 PM
    Moderator
     
     

    Thank you Peter.


    gsnu201208