Loop through named workbooks

K

KeriM

I'm working on some hypothetical code, but I imagine it will come i
handy somewhere down the line. Is it possible to list the names o
workbooks and then loop through all the names to perform an action o
each?

Let's say I have three workbooks named "Workbook 1", "Workbook 2" an
"Workbook 3"

Is there a way I can assign each of those names to a variable, or assig
them to an array, and then tell excel to loop through each of them an
tell me the name of the workbook in a message box
 
B

Ben McClave

Hi Keri,

This code should work. It should be relatively easy to adjust this as necessary.

Ben

Sub Books()
Dim wbk(1 To 3) As Workbook
Dim x As Long
Dim strMessage As String

'Change the wbk's below to whatever workbooks you need.
Set wbk(1) = ThisWorkbook
Set wbk(2) = ActiveWorkbook
Set wbk(3) = Workbooks("Book1")

strMessage = "Your workbook names are:" & vbCr & vbCr

For x = 1 To 3
strMessage = strMessage & wbk(x).Name & vbCr
With wbk(x)
'perform whatever you need to on the workbooks
End With
Next x

MsgBox strMessage

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top