Home » excel » excel – Loop through a range of cells on cell change to show next number in the sequence as cell's new value

# excel – Loop through a range of cells on cell change to show next number in the sequence as cell's new value

Questions:

I understand how to loop through a range,

``````For Each cell In Range("A1:A5")
If [condition] Then
End If
Next
``````

And I’m aware of OnChange event:

``````Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("A6")

If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
Call Macro
End If
End Sub
``````

However, I am not sure as to how achieve the following effect:
I have a cell A6 which shows the ‘result’ of formula, and I have another cell A7 with current interest rate which is used in the formula, I have multiple interest rates to go through, so I’ve declared them as a range (Interest_Rates).

My question is, how can I go through declared range to go to the next number once the A6 cell’s value has changed, and print it in cell A7 to get the result for another interest rate in the range, so I can print it in the table, and then find the highest rate.

Had to make some assumptions. For example, the code assumes that your formula is in cell A6 and that it actually looks like this: `=SUM(B3/100*A7)`. It also assumes that the formula is on a sheet named “Sheet1” and it puts the results in sheet “Formula Results” in column A.

``````Sub tgr()

Dim wb As Workbook
Dim wsData As Worksheet
Dim wsDest As Worksheet
Dim rInterestCell As Range
Dim rDest As Range

Set wb = ActiveWorkbook
Set wsData = wb.Sheets("Sheet1")
Set wsDest = wb.Sheets("Formula Results")

For Each rInterestCell In Range("Interest_Range").Cells
wsData.Range("A7").Value = rInterestCell.Value  'Put the interest cell value in range A7, which is used by the formula in A6
wsData.Calculate    'Update the formula result based on the new value in A7
Set rDest = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1)
If rDest.Row < 6 Then Set rDest = wsDest.Range("A6")    'Guarantee that A6 is the starting cell for the results
rDest.Value = wsData.Range("A6").Value   'Put the value only in a new row in the destination sheet
Next rInterestCell

End Sub
``````