I have a Userform which allows user to transfer item from ListBox1
to ListBox2
.
The items in ListBox2
are supposed to be filenames of excel files which are to be imported.
I have an overall idea of how this can operate but I am stuck with the problem that I cannot open the file with the item name in ListBox2
.
My question is, is it possible to "convert" the item name in a Listbox
to a string so it can be used as the filename for file opening?
I tried to use the MsgBox to test if the Listbox2(i) / ListBox2.Name(i) / ListBox2.List(i)
argument returns any values but unfortunately it doesn't. It always shows blank.
'This is the part where I try to open the files indicated in ListBox2
Dim directory = "my directory is here"
For i = 0 To ListBox2.ListCount - 1
Application.Workbooks.Open Filename:= directory & "\" & "FinalExcel.xlsx" 'This one is for testing to open file and it works.
Application.Workbooks.Open Filename:= directory & "\" & ListBox2(i)
Next
As mentioned in the comments, proper way to refer to ListBox
items in an array-like fashion is via the ListBox.List(i)
route.
Also a good practice would be to to check first whether the ListBox
is empty, because attempting to open an empty file (because of non-existent ListBox
field) will result in an error!
If Not ListBox2.ListCount = 0 Then
For i = 0 To ListBox2.ListCount - 1
Application.Workbooks.Open Filename:= directory & "\" & ListBox2.List(i)
Next i
End If
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.