For Each Loop

M

Matt

Could someone tell me why the following sub will not paset each book name
and sheet to its own workbook and sheet. I am obvously doing something
wrong but don't know what.


Sub TestSub()

Dim wk As Workbook
Dim ws As Worksheet


For Each wk In Workbooks
For Each ws In Worksheets
ws.Cells(1, 1) = ws.Name
ws.Cells(3, 1) = wk.Name
Next ws
Next wk



End Sub
 
W

Wolf

Sub TestSub()

Dim wk As Workbook
Dim ws As Worksheet


For Each wk In Workbooks
For Each ws In wk.Worksheets
ws.Cells(1, 1) = ws.Name
ws.Cells(3, 1) = wk.Name
Next ws
Next wk

End Sub

works for me

Best regards

Wolf
 
B

Bob Phillips

Matt,

The problem is caused by not referencing the correct workbook when iterating
through the worksheets. SO you need to add the wk. object qualifier to it


Sub TestSub()

Dim wk As Workbook
Dim ws As Worksheet

For Each wk In Workbooks
For Each ws In wk.Worksheets
ws.Cells(1, 1) = ws.Name
ws.Cells(3, 1) = wk.Name
Next ws
Next wk

End Sub

Incidentally, you can do this with worksheet function s

=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,100)

=MID(CELL("filename",A1),FIND("[",CELL("filename",A1))+1,FIND("]",CELL("file
name",A1))-FIND("[",CELL("filename",A1))-1)

--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)
 
M

Matt

Excellent, Thanks



Wolf said:
Sub TestSub()

Dim wk As Workbook
Dim ws As Worksheet


For Each wk In Workbooks
For Each ws In wk.Worksheets
ws.Cells(1, 1) = ws.Name
ws.Cells(3, 1) = wk.Name
Next ws
Next wk

End Sub

works for me

Best regards

Wolf
 

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