VBA Excel Function for returning file size in byte

2019-02-21 13:05发布

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

3条回答
我只想做你的唯一
2楼-- · 2019-02-21 13:46

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

查看更多
Viruses.
3楼-- · 2019-02-21 13:47

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).

查看更多
虎瘦雄心在
4楼-- · 2019-02-21 13:48

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 ***
查看更多
登录 后发表回答