Trying to create an array of files that I can later ‘cycle through’ to pull information from each file (the files are laid out identically / forms in excel). Receiving ‘6’ Overflow error, suspecting this is an error caused by my Loop?
Sub WorkOrderList()
'This compiles an array of Files by picking from the folder
Dim objFileDialog As Office.FileDialog
Dim SelectedFile As Variant
Dim arFiles() As Variant
Dim myCount As Integer
Set objFileDialog = Application.FileDialog(msoFileDialogFilePicker)
With objFileDialog
.AllowMultiSelect = True
.ButtonName = "Select"
.Title = "Work Order Picker"
If (.Show > 0) Then
End If
If (.SelectedItems.Count > 0) Then
For Each SelectedFile In .SelectedItems
Do Until SelectedFile = ""
myCount = myCount + 1
ReDim Preserve arFiles(1 To myCount)
arFiles(myCount) = SelectedFile
Loop
Next SelectedFile
Else
End If
End With
Set objFileDialog = Nothing
End Sub
I would expect a resulting array arFiles with each element of the array being the files selected from the msoFileDialogFilePicker.
You don’t need to nest the loops like that to copy them. You get the overflow because you have a Do
loop that is impossible to exit:
For Each SelectedFile In .SelectedItems
Do Until SelectedFile = "" '<-- This will never be true.
myCount = myCount + 1
ReDim Preserve arFiles(1 To myCount)
arFiles(myCount) = SelectedFile
Loop
Next SelectedFile
This will keep incrementing myCount
until it overflows. Given that the size of the array is always going to be the same as the number of selected items, I’d suggest using a simple For
loop instead. Size the array once (as @TimWilliams suggested), then just use the indexer on SelectedItems
to copy them:
myCount = .SelectedItems.Count
If myCount > 0 Then
ReDim arFiles(1 To myCount)
Dim idx As Long
For idx = 1 To myCount
arFiles(idx) = .SelectedItems(idx)
Next
End If
Answer:
With objFileDialog
.AllowMultiSelect = True
.ButtonName = "Select"
.Title = "Work Order Picker"
.Show
If (.SelectedItems.Count > 0) Then
ReDim Preserve arFiles(1 To .SelectedItems.Count)
For Each SelectedFile In .SelectedItems
myCount = myCount + 1
arFiles(myCount) = SelectedFile
Next SelectedFile
End If
End With
Tags: arraysexcel, file, select