Search code examples
vbaexcelduplicatesformula

Use vba to write formula in cell


My basic formula is : =IF(COUNTIF($A:$A,$A2)=COUNTIFS($A:$A,$A2,$B:$B,$B2),"OK","NOT OK")

I use it to know if there are duplicate in column A, and i check the value in B.

ID    Age   My formula

1     15    NOT OK
2     50    OK
2     50    OK
3     35    OK
1     15    NOT OK
1     16    NOT OK

Now i'd like to write it with VBA, so I record a maccro, select the cell, press F2 then press Enter. I get:

ActiveCell.FormulaR1C1 = _
 "=IF(COUNTIF(C3,RC[-10])=COUNTIFS(C3,RC[-10],C12,RC[-1]),""PRODUIT"",""ARTICLE"")"

Alright, it work. Now I'd like to use this formula with a new column:

Id    Age   Age formula   Money   Money formula   Value3   Value3 formula   ...

1     15    NOT OK        150     OK              ...      ...
2     50    OK            5       NOT OK          ...
2     50    OK            800     NOT OK
3     35    OK            80      OK
1     15    NOT OK        150     OK
1     16    NOT OK        150     OK

I know how to use the formular "by hand" and I know how to use it for a single cell in vba, but I don´t know hot to use it in a loop. (I have to use the formula on 25+ column that's why I need loop and variable)

Sorry for my bad english, Thanks in advance


Solution

  • You just need to edit the 25 in For r = 2 To 25 to the last row you want to fill with the formula.

    Code:

    'Loops throug the rows
    For r = 2 To 25
        'Loops throug the columns
        For c = 13 To 69 Step 2
            'Converts the column-index into the column-letter
            Dim col As String
            col = Split(Cells(r, c - 1).Address(True, False), "$")(0)
            'Writes the formula into the cell
            Cells(r, c).Formula = "=IF(COUNTIF($C:$C,C" & r & ")=COUNTIFS($C:$C,C" & r & ",$" & col & ":$" & col & "," & col & r & "),""PRODUIT"",""ARTICLE"")"
        Next
    Next