# Basic Variable Problem

#### hdbkiwi

##### New Member
Hi Everyone,

First off, a huge thanks to everyone helping out here - I love this community and have learned so much from reading other threads.

I'm trying to do a very simple for loop that cycles through sheets and executes a long code within that sheet. However, for some reason, the for loop is not working and the code only executes on the first sheet. My code is below:
Code:
``````Sub RowDel()

x = Worksheets.Count
For J = x To 2 Step -1

With Sheets(J) 'example code to execute
Rows("1:1").Delete Shift:=xlUp
Rows("3:3").Delete Shift:=xlUp
End With

Next J
End Sub``````
Any ideas?

Last edited by a moderator:

#### RoryA

##### MrExcel MVP, Moderator
Your With block doesn't actually do anything currently as you haven't qualified the Rows property calls:
Rich (BB code):
``````With Sheets(J) 'example code to execute
.Rows("1:1").Delete Shift:=xlUp
.Rows("3:3").Delete Shift:=xlUp
End With``````
is what you need.

#### hdbkiwi

##### New Member
Oh goodness, so basic, thank you very much! Can't believe I missed that.

It's gone through and is now deleting the first rows which is amazing.

I thought what I would do next is delete out rows that are of a certain colour, but in order to do that I need to reset the used range in each worksheet.

I then go on in my code to write:

Dim rng As Range
Set rng = Sheets(J).UsedRange
rng.Select

RowCount = rng.Rows.Count
For i = RowCount To 2 Step -1
If Cells(i, 2).Interior.ColorIndex = 14 Or Cells(i, 2).Interior.ColorIndex = 43 Then Cells(i, 1).EntireRow.Delete
Next i

--

However, it stops at "rng.Select" with a Run-time error of '1004' Select method of Range class failed.

Any ideas?

#### RoryA

##### MrExcel MVP, Moderator
You cannot select a range on a sheet without activating that sheet first. However, there is no need to select the range so simply remove that line. And note that you have not qualified your Cells calls with a worksheet...

1,082,133
Messages
5,363,341
Members
400,729
Latest member
Lisa McConachy

### This Week's Hot Topics

• populate from drop list with multiple tables
Hi All, i have a drop list that displays data, what i want is when i select one of those from the list to populate text from different tables on...
• Find list of words from sheet2 in sheet1 before a comma and extract text vba
Hi Friends, Trying to find the solution on my task. But did not find suitable one to the need. Here is my query and sample file with details...
• Dynamic Formula entry - VBA code sought
Hello, really hope one of you experts can help with this - i've spent hours on this and getting no-where. .I have a set of data (more rows than...