0

I am trying to assign If formula to certain cell every 16th row. Formula needs to compare values of cells in J, K and L columns and gives Pass or Fail Result.

I am having issues making this If formula work in a loop. Please Help! My Code is below.

First I am getting compile error saying " Expected end of statement"

Second, is there any other way to make these work? I need same formula applied to Cell M5 to M789 at every 16th cell.

For a = 5 To 789 Step 16

   Range("M" & a).FormulaR1C1 = "=IF(Range("J" & a)>= Range("K" & a),IF(Range("J" & a))<= Range("L" & a),""PASS"", ""FAIL""),""FAIL"")"
7
  • 3
    1) You need .Formula instead of .FormulaR1C1. 2) Don't use Range within a formula - that's mixing VBA into regular worksheet formulas. You can't use Range(J5) in a worksheet - just J5. Commented Nov 7, 2019 at 15:43
  • Thanks. Instead of Range, what else can I use to get values of J5 to J789, K5 to K789 and L5 to L789 cells within a loop? Commented Nov 7, 2019 at 15:45
  • Just "J", "K", and "L" - drop the Range calls from the formula part. Commented Nov 7, 2019 at 15:45
  • Range("M" & a).Formula = "=IF(("J" & a)>=("K" & a),IF(("J" & a)<= ("L" & a),""PASS"", ""FAIL""),""FAIL"")" OK i removed the Range part and still gives me compile error for "expected end of statement" with "J" highlighted. Commented Nov 7, 2019 at 15:50
  • 1
    One could also ask the question if you really need these cells to be filled with a formula. What purpose does it have. Are J, K and L column values going to change? Otherwise you are doing unnecessary calculations. Commented Nov 7, 2019 at 16:02

1 Answer 1

3
  1. You need .Formula instead of .FormulaR1C1 - you are not using R1C1 references.

  2. Remove the Range calls from the formula part. That's mixing VBA with regular worksheet formula syntax.

  3. You can simplify the formula using AND. And in this case you don't need to concatenate a in at all. Excel is smart enough to update relative references.

Sub Test()
    Dim myFormula As String
    myFormula = "=IF(AND(J5>=K5,J5<=L5),""PASS"",""FAIL"")"

    Dim a As Long
    For a = 5 To 789 Step 16
        Range("M" & a).Formula = myFormula
    Next
End Sub
Sign up to request clarification or add additional context in comments.

Comments

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.