VBA Excel函数用于返回字节中的文件大小

我希望在Excel 2010中使用VBA返回同一个文件夹中的某些文件的文件大小或不同的文件大小。我该如何解决这个问题?

有一个非常好的和简单的VBAfunction,到目前为止还没有提到, FileLen :

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

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

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

这里如何在Excel中使用它单元格:

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

如果你有一个德语Windows比:

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

这里是VBA模块的function:(只需启用开发工具,复制并粘贴到一个新的模块)

 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 ***