I have never done a loop in VBA before and i am stuck. I have found numerous example on the web and here and can’t seem to tweak it to get it to do what i want. So i would appreciate your help!
Basically i am creating a document revision table, the current revision comes in from another sheet and is entered into a cell, the loop i want to take that cell – 1 in the next cell down until it gets to 1. Example if
.range("A1") = 5 then A2 = 4, A3 = 3 A4 = 2 and A5 = 1. This is my attempt at it.
Sub RevisionLoop() Dim Rev As String Dim i As Integer i = 0 Rev = ThisWorkbook.Worksheets(1).Range("A1") Do While Rev > 0 Range("A1").Offset(i, 0) = Rev i = i - 1 Rev = Rev - 1 Loop End Sub
The minimum number will be 1. Can you advise where i have gone wrong please? Also i am not to sure if my first
Dim should be a
String as i don’t fully understand these yet. :-S Thank you!
The first thing to do is find the last row in your sheet.
Then instead of the Do While loop, use a loop instead.
Your loop should include “Step -1” in order to work from last to first (reverse order).
Sub FindLastRowInOneColumn_then_LoopInReverse() 'Find the last used row in a Column: column A in this example Dim LastRow As Long With ActiveSheet LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With 'Loop Through All Rows in Reverse Order For x = LastRow To 0 Step -1 'Change The Value In Column A to x ActiveSheet.Cells(x, 1).Value = x Next x End Sub