VBA openworkbooks using file variable

jimsjams

New Member
Joined
Nov 6, 2008
Messages
29
Hello all and Happy Friday,

I was hoping somebody might know if it is possible to open files using a variable and loop. I want to define the name and path of the files so they can be easily changed later and then loop through them so that I can extract some data from each one.

I thought something like this should work:

Sub openworkbooks()

myfile1 = "c:\test1.xls"
myfile2 = "c:\test2.xls"
myfile3 = "c:\test3.xls"
myfile4 = "c:\test4.xls"
myfile5 = "c:\test5.xls"

For i = 1 To 5

Workbooks.Open Filename:=myfile & i
'copy some data from workbook

Next i

End Sub

This gives an error saying that 'myfile1.xls' doesn't exist.
However if i use workbooks.open Filename:=myfile1 then that would work and open the correct workbook.

Any ideas?

Thanks,

James
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
Try:
Code:
Sub openworkbooks()
Dim myFile(1 to 5) as String
myfile(1) = "c:\test1.xls"
myfile(2) = "c:\test2.xls"
myfile(3) = "c:\test3.xls"
myfile(4) = "c:\test4.xls"
myfile(5) = "c:\test5.xls"

For i = 1 To 5

Workbooks.Open Filename:=myfile(i)
'copy some data from workbook

Next i

End Sub
 
Upvote 0
Maybe:

Code:
Sub openworkbooks()
Dim i As Long
For i = 1 To 5
Workbooks.Open Filename:="C:\test" & i & ".xls"
'copy some data from workbook
Next i
End Sub

Dom
 
Upvote 0
Rory and Dom,

Thanks so much for the help. Works perfectly.

Rory - I think that's twice you've helped me already this morning and it's only 9am here!

Thanks again,

James
 
Upvote 0

Forum statistics

Threads
1,223,228
Messages
6,170,871
Members
452,363
Latest member
merico17

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top