我试图弄清楚如何在调用自身的函数中返回字符串数组。该功能可浏览特定路径内的所有文件夹和子文件夹,以生成文本文件及其位置的列表。现在,子例程为All_Folder
。我以前曾尝试使All_Folder
成为一个函数,并尝试从该函数返回值,但这无济于事。现在这是我的代码:
Public file_locations() As String
Sub Some_Subroutine()
Dim pathway As String: pathway = "C:\Users"
Dim FileSystem As Object
Set FileSystem = CreateObject("Scripting.FileSystemObject")
All_Folder FileSystem.GetFolder(pathway)
...
End Sub
Public Sub All_Folder(Folder)
Dim filetype as string: filetype = "*.txt"
Dim Counter As Integer: Counter = 0
Dim SubFolder: Dim File
For Each SubFolder in Folder.SubFolders
All_Folder SubFolder
Next
For Each File in Folder.Files
If Dir(Folder & "\" & filetype) <> "" Then
ReDim Preserve file_locations(Counter)
file_locations(Counter) = CallByName(File, Path, VbGet)
Counter = Counter + 1
End If
Next
End Sub
我的问题是,每次运行此函数时,file_locations
中的输出始终被下一个调用目录中的内容覆盖。
在子例程All_Folder
的末尾有列表,我只需要能够将其存储/追加到当前file_locations
列表中即可。
答案 0 :(得分:0)
按照Tim Williams和PeH的建议,我没有将Counter
设置为全局变量。这将是更新的代码:
Public file_locations() As String
Public Counter As Integer
Sub Some_Subroutine()
Dim pathway As String: pathway = "C:\Users"
Counter = 0
Dim FileSystem As Object
Set FileSystem = CreateObject("Scripting.FileSystemObject")
All_Folder FileSystem.GetFolder(pathway)
...
End Sub
Public Sub All_Folder(Folder)
Dim filetype as string: filetype = "*.txt"
Dim SubFolder: Dim File
For Each SubFolder in Folder.SubFolders
All_Folder SubFolder
Next
For Each File in Folder.Files
If Dir(Folder & "\" & filetype) <> "" Then
ReDim Preserve file_locations(Counter)
file_locations(Counter) = CallByName(File, Path, VbGet)
Counter = Counter + 1
End If
Next
End Sub
谢谢你们两个帮助我。