Results 1 to 4 of 4

Thread: trying to loop range but getting error

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2006
    Posts
    97

    trying to loop range but getting error

    Hi Friends

    I have used for next to loop through range but I got subscript out of range

    here is my code.

    Code:
     Dim i As Long
        For i = 1 To Sheets("Sheet2").Range(A1, S1000).Rows
            If Sheets("Sheet1").Range("F5") = Cells(1, "R") Then
             Selection.Rows(i).EntireRow.Delete
            End If
        Next i
        Range("F22") = i
    can any one help me what is the problem?

    thanks

  2. #2
    New Member
    Join Date
    Jun 2011
    Posts
    8

    Re: trying to loop range but getting error

    I'm no expert but Cells(1,"R") must be an error as the format is Cells(Row,Column) and I presume you want the value, i.e. Cells(Row,Column).Value.

  3. #3
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: trying to loop range but getting error

    Cells(1,"R") must be an error as the format is Cells(Row,Column)
    it will accept a string or the column letter

    If Sheets("Sheet1").Range("F5") = Cells(1, "R") Then
    surely that should be cells(i, "R")

    which line gives the error at what value of i

    as the code is it should delete no rows or every row
    remember when you delete rows from a loop the row index changes, so you will skip the row after the deleted row
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  4. #4
    New Member
    Join Date
    Jun 2011
    Posts
    4

    Re: trying to loop range but getting error

    Use a variable and store last column and LastRow
    then use two loop

    Last Columns = Sheets("Sheet1").Cells(1, Columns.Count).End(xlToLeft).Column

    LastRow = Cells(Cells.Rows.Count,"A").End(xlUp).Row

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width