vb FormatBytes

Quick function to format bytes in Excel / VBA into human-readable strings.

Function FormatBytes(bytes As Double, Optional places As Integer = 0) As String
    If bytes >= 1024 ^ 5 Then
        FormatBytes = Round(bytes / (1024 ^ 5), places) & " Pb"
    ElseIf bytes >= 1024 ^ 4 Then
        FormatBytes = Round(bytes / (1024 ^ 4), places) & " Tb"
    ElseIf bytes >= 1024 ^ 3 Then
        FormatBytes = Round(bytes / (1024 ^ 3), places) & " Gb"
    ElseIf bytes >= 1024 ^ 2 Then
        FormatBytes = Round(bytes / (1024 ^ 2), places) & " Mb"
    ElseIf bytes >= 1024 ^ 1 Then
        FormatBytes = Round(bytes / (1024 ^ 1), places) & " Kb"
    Else
        FormatBytes = Round(bytes, places) & " bytes"
    End If
End Function
← Back to Blog All Articles →