创建一个功能数组来存储文件夹中文件的名称

创建一个功能数组来存储文件夹中文件的名称

我想创建一个功能数组,用于存储特定文件夹中的所有文件的名称

这就是我尝试过的……

Function number_of_file(i As Integer) As Variant

Dim file_object As Object
Dim files_in_folder() As Variant

Set file_object = CreateObject("scripting.filesystemobject").getfolder("D:\ls")

i = 0
For Each obj In file_object.Files
ReDim files_in_folder(i)
    files_in_folder(i) = obj.Name
    i = i + 1
Next obj

number_of_files = files_in_folder
End Function


sub test()
files_in_folder(2)
end sub

答案1

这将获取文件名数组,并将该数组存储在列中A

Sub MAIN()
   Dim FolderOfInterest As String, i As Long
   FolderOfInterest = "C:\TestFolder"
   Dim ary()
   ary = files_in_folder(FolderOfInterest)
   MsgBox "There are " & UBound(ary) & " files in folder " & FolderOfInterest
   '
   '  Now store the array in a worksheet column
   '
   i = 1
   For Each a In ary
      Cells(i, "A").Value = a
      i = i + 1
   Next a
End Sub

Public Function files_in_folder(folderS As String) As Variant
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set folder = fso.GetFolder(folderS)
   ReDim temp(1 To folder.Files.Count)

   i = 1
   For Each file In folder.Files
      temp(i) = file.Name
      i = i + 1
   Next file

   files_in_folder = temp
End Function

笔记:

该函数返回一个字符串数组,(一个依据). 文件数量就是该数组的上限。

相关内容