Either
Redim arr(0) as String
then
arr(ubound(arr)) = "newFilename"
ReDim Preserve arr(ubound(arr)+1)
then after the loop
ReDim Preserve arr(ubound(arr)-1)
to shrink it by the last empty element.
As alternative to using an array. You can use Collection
or Dictionary
.
Collections do not need to know their size at initialization. You add items using their Add()
method.
To see a real example of implementation see this
and that
If you do decide to go with the Dir()
function and iterate to see how many files there are here's a sample function
Sub Main()
ReDim arr(FilesInDirectoryCount("C:\...")) As String
End Sub
Function FilesInDirectoryCount(path As String)
Dim f As String, c As Long
f = Dir$(path)
Do While Len(f) <> 0
c = c + 1
f = Dir$
Loop
FilesInDirectoryCount = c
End Function
or use this
Sub CountFiles()
Dim strDir As String
Dim fso As Object
Dim objFiles As Object
Dim obj As Object
Dim lngFileCount As Long
strDir = "C:\path..."
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFiles = fso.GetFolder(strDir).Files
lngFileCount = objFiles.count
MsgBox lngFileCount
Set objFiles = Nothing
Set fso = Nothing
Set obj = Nothing
End Sub