How to return KB, MB and GB from Bytes using a public function

前端 未结 6 1549
囚心锁ツ
囚心锁ツ 2021-02-10 01:49

I\'m writing a "function" that returns a file\'s size (in B, KB, MB, GB).

The VB.Net code always gets the size in bytes first, so when a file\'s size (in Bytes)

6条回答
  •  一整个雨季
    2021-02-10 02:10

    Here is how I do it, below is a VBA function that I use in Microsoft Access that can easily be converted to VB or VBScript, etc.

    Public Function FormatFileSize(ByVal lngFileSize As Long) As String
    
      Dim x      As Integer:      x = 0
      Dim Suffix As String:  Suffix = ""
      Dim Result As Single:  Result = lngFileSize
    
      Do Until Int(Result) < 1000
         x = x + 1
         Result = Result / 1024
      Loop
    
      Result = Round(Result, 2)
    
      Select Case x
             Case 0
                  Suffix = "Bytes"
             Case 1 'KiloBytes
                  Suffix = "KB"
             Case 2 'MegaBytes
                  Suffix = "MB"
             Case 3 'GigaBytes
                  Suffix = "GB"
             Case 4 'TeraBytes
                  Suffix = "TB"
             Case 5 'PetaBytes
                  Suffix = "PB"
             Case 6 'ExaBytes
                  Suffix = "EB"
             Case 7 'ZettaBytes
                  Suffix = "ZB"
             Case 8 'YottaBytes
                  Suffix = "YB"
             Case Else
                  Suffix = "Too big to compute :)"
      End Select
    
      FormatFileSize = Format(Result, "#,##0.00") & " " & Suffix
    
    End Function 'FormatFileSize
    

提交回复
热议问题