gpt4 book ai didi

vba - Excel VBA高效获取文件名函数

转载 作者:行者123 更新时间:2023-12-01 22:48:24 28 4
gpt4 key购买 nike

我需要使用 Excel 2010 中的 VBA 从远程服务器上的文件夹中获取文件名集合。我有一个可以工作的函数,并且在大多数情况下它可以完成这项工作,但是远程服务器经常出现糟糕的情况,严重网络性能问题。这意味着循环遍历 300 个文件以将其名称放入集合中可能需要 10 分钟,文件夹中的文件数量可能会增长到数千个,所以这是不可行的,我需要一种方法来获取所有文件名在单个网络请求中并且不循环。我相信它连接到远程服务器需要时间,因此单个请求应该能够相当快地一次性获取所有文件。

这是我目前拥有的功能:

Private Function GetFileNames(sPath As String) As Collection
'takes a path and returns a collection of the file names in the folder

Dim oFolder As Object
Dim oFile As Object
Dim oFSO As Object
Dim colList As New Collection

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(folderpath:=sPath)

For Each oFile In oFolder.Files
colList.Add oFile.Name
Next oFile

Set GetFileNames = colList

Set oFolder = Nothing
Set oFSO = Nothing

End Function

最佳答案

这个速度快如闪电:

  Sub filesTest()
Dim x() As String
x = Function_FileList("YOUR_PATH_AND_FOLDER_NAME")
Debug.Print Join(x, vbCrLf)
End Sub

调用此函数:

 Function Function_FileList(FolderLocation As String)
Function_FileList = Filter(Split(CreateObject("wscript.shell").exec("cmd /c Dir """ & FolderLocation & """ /b /a-d").stdout.readall, vbCrLf), ".")
End Function

关于vba - Excel VBA高效获取文件名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26262962/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com