0

I want to insert an if statement in diffent sheets in excel. I therefore wrote the following:

 Sub Final_Insert_Columns()


     Dim month As Variant
     Dim months As Variant
     months = Array("07 AMSTERDAM", "07 ARNHEM")

    For Each month In months

        Sheets(month).Activate
        Range=("n4").Formula = "IF(OR(T4=0;T4="PAS");"X"; (AJ4/AK4))

    Next
 End sub

There seems to be a problem however with this part:

 Range=("n4").Formula = "IF(OR(T4=0;T4="PAS");"X"; (AJ4/AK4))
 Compile error: expected end of statement.

Any thoughts on how I should get this working?

Community
  • 1
  • 1
Marc van der Peet
  • 323
  • 1
  • 6
  • 14
  • Unrelated to the quotes problem, shouldn't that `Range=("n4")` be `Range("n4")`? A typo while writing the question perhaps? Or I'm missing something? – ssarabando Aug 24 '15 at 15:28

2 Answers2

1

Instead of

Range=("n4").Formula = "IF(OR(T4=0;T4="PAS");"X"; (AJ4/AK4))

Use

Range("n4").Formula = "=IF(OR(T4=0, T4=""PAS""),""X"", (AJ4/AK4))"

You need to use "" to escape " inside a string. Also -- I think you need commas rather than semicolons in the formula - but maybe that is a regional setting and you can leave the semicolons alone (I had to use commas to test it on my machine). You also had a stray equals sign at the front and a missing equals sign in the formula string. If you don't include "=" before the IF then Excel will treat it as a string that you are inserting in the cell.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
1

Your code needs to be revised to reflect the fact that (1) you need to include actual quotation marks within your formula, where it currently actually just ends VBA's own use of quotation marks, and (2) you need to end the whole thing with quotation marks so that VBA knows that your formula text is complete. Like so:

Range=("n4").Formula = "IF(OR(T4=0;T4=""PAS"":);""X""; (AJ4/AK4))"

Another method is to replace the insertion of quotation marks with the ASCII character 34, as suggested here https://stackoverflow.com/a/28507279/5090027.

Community
  • 1
  • 1
Grade 'Eh' Bacon
  • 3,773
  • 4
  • 24
  • 46