If statement within For each ws in Workbook

tp2468

New Member
Joined
Mar 5, 2009
Messages
45
Hi All,

Trying to add worksheet names to a listbox based on a set criteria. The one line of code that doesn't work is.
If Workbooks(filename).ws.Cells(7, 2) = "Surname" Then

Not sure what it should be. ws is dimmed as worksheet
Code:
'I want worksheets added to the listbox only if cell(7,2) is equal to "Surname"
With Me.ListBox1
Me.ListBox1.Clear
    
    For Each ws In Workbooks(filename).Worksheets
        If Workbooks(filename).ws.Cells(7, 2) = "Surname" Then ' this line doesn't work.
        .AddItem ws.Name
        Else
        End If
    Next
End With
 

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
Is this code running from a separate workbook than the one you are looping through?
If so, are both files open in the same Excel session at the time you are running this?
 
Upvote 0
That line should be
Code:
ws.Cells(7, 2) = "Surname" Then
The ws object is part of the relevant workbook, so you don't reference the workbook.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,969
Messages
6,175,680
Members
452,667
Latest member
vanessavalentino83

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