'Validation with custom formula in string variable

I'm struggling with data validation for the range of cells in a For loop.

I want to use a custom formula with COUNTIF to check for unique values.

I found examples and tutorials on the internet.

I get:

Run-time error 1004: Application-defined or object-defined error

pointing to

.Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:=valFormula

This validation rule is called once in for loop, for the specified row.

Dim valFormula As String

For Each cell In Sheets("B").Range(Cells(4, 2), Cells(LastRow, 2))
     
    If cell.Row = 54 Or cell.Row = 55 Then
         '<some code>
    
    ElseIf cell.Row = 4 Then
        valFormula = "=COUNTIF($B$4:" & Cells(4, LastColumn).Address & ";" & cell.Address(0,0) & ")<2"
        With Range(Cells(cell.Row, 2), Cells(cell.Row, LastColumn)).validation
            .Delete
            .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:= _
              xlBetween, Formula1:=valFormula
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .ShowInput = True
            .ShowError = True
        End With
        '<some code>

I recorded a macro when using Excel interface to use auto-generated code as a template but when I copied it into the for loop I also get this error.

Raw Formula1 string:

Formula1:="=LICZ.JEŻELI($B$4:$CE$4;B4)<2"

LICZ.JEŻELI is a local version of COUNTIF.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source