Home » excel » excel – vba – Call a function in a loop

excel – vba – Call a function in a loop

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to call an homemade function (GetCoordinates) in a loop and apply it at each loop step.

I have a column with data (Starting at L2) and I need to apply my personnal function GetCoordinates to this data and write the result on the column next to it (so starting at M2)

NumRows = Range("L2", Range("L2").End(xlDown)).Rows.Count
      Range("L2").Select
      For x = 1 To NumRows
         Selection.Offset(, 1).Formula = "=GetCoordinates(L&x)"
         ActiveCell.Offset(1, 0).Select
      Next

My problem is that I don’t know how to apply my function to each cell. How should it be written so that the function is called for each cell in the loop? (The GetCoordinates function works fine)

How to&Answers:

Try putting in all the formulas without a loop. To write te formulas in column M and use column L as the formulas argument then use,

 Range(cells(2, "M"), cells(rows.count, "L").End(xlup).offset(0, 1)).Formula = _
     "=GetCoordinates(L2)"

Your own might have been closer with,

Selection.Offset(, 1).Formula = "=GetCoordinates(L" & x & ")"

But you were mismatching Do … While and For … Next loops.

Answer:

Try this

 NumRows = Range("L" & Rows.Count).End(xlUp).Row

  For x = 2 To NumRows
     Cells(x, "M").Value = GetCoordinates(Cells(x, "L"))
  Next