VBA Excel函数用于以字节为单位返回文件大小

xmu*_*mux 13 size vba byte function excel-vba

我希望在Excel 2010中使用VBA返回同一文件夹或不同文件中某些文件的文件大小.

Zyg*_*ygD 24

有一个非常好用且简单的VBA函数,到目前为止还没有提到,FileLen:

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

它以字节为单位返回文件的大小.

结合循环遍历目录中的文件,可以实现您最初想要的(获取文件夹中文件的大小).

  • 不幸的是,除非您使用一些特殊的数学运算,否则它仅适用于<2GB的文件,然后将其限制为<4GB。 (3认同)

xmu*_*mux 14

这里如何在Excel Cell中使用它:

 =GetDirOrFileSize("C:\Users\xxx\Playground\","filename.xxx")
Run Code Online (Sandbox Code Playgroud)

如果你有一个德国Windows比:

=GetDirOrFileSize("C:\Users\xxx\Playground\";"filename.xxx")
Run Code Online (Sandbox Code Playgroud)

以下是VBA模块的功能:(只需启用开发人员工具,然后将其复制并粘贴到新模块中)

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 ***
Run Code Online (Sandbox Code Playgroud)