3

Im trying to use For loop on an excel column. This is my code:

   For Each c In Worksheets("sheet1").Range("A1:A5000").Cells
        c.Offset(0, 1).Range("A1").Value = Right((Left(c, 13)), 7)
   Next

it works ok the problem is with the

Range("A1:A5000")

my sheet has less then 1000 rows but it can grow and I want to be able to use the loop only on the rows that have data in them. how can I change it to go from A1 to the last not empty row?

3

2 Answers 2

2
Dim RowIndex As Long
RowIndex = 1

Dim c

While Not IsEmpty(Worksheets("sheet1").Cells(RowIndex, 1))
    Set c = Worksheets("sheet1").Cells(RowIndex, 1)
    c.Offset(0, 1).Range("A1").Value = Right((Left(c, 13)), 7)
    RowIndex = RowIndex + 1
Wend
Sign up to request clarification or add additional context in comments.

Comments

1

You may try this ...

Dim r As Range

Set r = Range("A65536").End(xlup)

For Each c In Worksheets("sheet1").Range("A1:" & r.Address).Cells
   c.Offset(0, 1).Range("A1").Value = Right((Left(c, 13)), 7)
Next

1 Comment

Should be Set r = Cells(Rows.Count,"A").End(xlup) to handle xl07 and onwards - the current formula was appropriate for xl03 and earlier but many more rows now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.