Would appreciate any guidance in understanding why the following code only returns the last value of an array. I and trying to return the file name of all open Workbooks then select whatever Workbook based on its Array index. The following code finds and returns the name of all open Workbooks but only assigns and returns the last found name to the Array. I am using Preserve with ReDim which accoring to my research should keep adding each File Name to the Array. For my testing I was using four open Workbooks but it only returns the name of the fourth found. Code is:
Sub SelectWB()
Dim xWBName As String
Dim xWb As Workbook
Dim xSelect As String
Dim WkbCount As Variant
Dim i As Variant
Dim MyArray As Variant
Dim FilName As String
xNum = Application.Workbooks.Count
For Each xWb In Application.Workbooks
WkbCount = WkbCount + 1
xWBName = xWb.Name
'xWBName = xWBName & WkbCount & " - " & xWb.Name & vbCrLf
MyArray = Array(xWBName)
ReDim Preserve MyArray(WkbCount) As Variant
MyArray(WkbCount) = xWBName
Next
For i = LBound(MyArray) To UBound(MyArray)
Debug.Print MyArray(0)
Debug.Print MyArray(1)
Debug.Print MyArray(2)
Debug.Print MyArray(3)
Next i
FilName = MyArray(0)
xTitleId = "Open Workbooks"
'xSelect = Application.InputBox("Enter one of the workbooks below:" & vbCrLf & xWBName, xTitleId, "", Type:=2)
xSelect = FilName
Application.Workbooks(xSelect).Activate
End Sub
The issue in your code lies in the placement of the line
MyArray = Array(xWBName). Currently, you are assigning a new array with only one element toMyArrayin each iteration of the loop. Therefore, in each iteration, you are overwriting the previous array with a new array containing only the current workbook name.To fix this issue, you need to move the line
MyArray = Array(xWBName)outside the loop and initializeMyArrayas an empty array before the loop. Then, inside the loop, you can useReDimPreserve to increase the size of the array and assign the workbook name to the appropriate index.Here's the modified code: