Reputation: 65
This piece of code detects the value in cell W14 then makes it a negative absolute value. It should make every value that exists in column W, starting after W14 be a negative absolute value. When I run it though, it will loop forever, making every single cell after W14 a negative absolute value even if a value does not exist there. How can I stop the loop after the last cell with a value in it has been turned negative?
For Each r In Range(Range("W14"), Range("W14").End(xlDown))
r.Value = -Abs(r.Value)
Next r
Upvotes: 0
Views: 983
Reputation: 7735
Another way to do it:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "W").End(xlUp).Row
'get the last row with data on Column W
For i = 14 To LastRow
ws.Cells(i, "W").Value = -Abs(ws.Cells(i, "W").Value)
Next r
End Sub
Upvotes: 1
Reputation:
It will only loop for to the end of the Worksheet if Range("W14")
is the last non-empty cell in the column. This is why you should use a bottom up approach.
For Each r In Range("W14", Range("W" & Rows.Count).End(xlUp))
r.Value = -Abs(r.Value)
Next r
Upvotes: 4