问题
I am trying to figure out how to return a string array in a function that calls itself. It is a function that looks through all folders and subfolders within a specific path to generate a list of text files and where they are located. Right now, the subroutine is All_Folder
. I have previously tried making All_Folder
a function, and trying to return the value from the function, but that has gotten me nowhere. This is my code now:
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
My problem is that every time this function is ran, the output in file_locations
is always overwritten by what is in the next called directory.
I have the list by the end of the subroutine All_Folder
, I just need to be able to store/append it to the current file_locations
list.
回答1:
As Tim Williams and PeH suggested, I had not set my Counter
as a global variable. Here would be the updated code:
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
Thanks to you two for helping me out.
来源:https://stackoverflow.com/questions/55264407/return-array-in-self-calling-function-in-vba