VBA Excel Function for returning file size in byte

2019-02-21 13:22发布

问题:

I wish to return the file size of some files in the same folder or in a different one with VBA in Excel 2010.

回答1:

There is a very nice and simple VBA function, which was not mentioned so far, FileLen:

FileLen("C:\Temp\test file.xls")

It returns the size of the file in bytes.

In combination with looping through files in a directory it's possible to achieve what you originally wanted (get sizes of files in a folder).



回答2:

Here how to use it in Excel Cell:

 =GetDirOrFileSize("C:\Users\xxx\Playground\","filename.xxx")

If you have a german Windows than:

=GetDirOrFileSize("C:\Users\xxx\Playground\";"filename.xxx")

Here is the function for the VBA modul: (Just enable the Developer tools, and copy and paste this into a new modul)

Function GetDirOrFileSize(strFolder As String, Optional strFile As Variant) As Long

'Call Sequence: GetDirOrFileSize("drive\path"[,"filename.ext"])

   Dim lngFSize As Long, lngDSize As Long
   Dim oFO As Object
   Dim oFD As Object
   Dim OFS As Object

   lngFSize = 0
   Set OFS = CreateObject("Scripting.FileSystemObject")

   If strFolder = "" Then strFolder = ActiveWorkbook.path
   If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
   'Thanks to Jean-Francois Corbett, you can use also OFS.BuildPath(strFolder, strFile)

   If OFS.FolderExists(strFolder) Then
     If Not IsMissing(strFile) Then

       If OFS.FileExists(strFolder & strFile) Then
         Set oFO = OFS.Getfile(strFolder & strFile)
         GetDirOrFileSize = oFO.Size
       End If

       Else
        Set oFD = OFS.GetFolder(strFolder)
        GetDirOrFileSize = oFD.Size
       End If

   End If

End Function   '*** GetDirOrFileSize ***


回答3:

This is in reply to the question regarding the use of the semicolon ; as a parameter seperator.

In locals (like US) which use the point/fullstop . as a decimal point, the coma , is used as a list seperator, in this case as a seperator in the list of parameters to VBA functions and procedures.

In other locals (like DE and Europe in general), where the decimal point is the coma , things would get confusing if the same symbol was used as a list seperator, so the semcolon ; is being used instead