首页 > 解决方案 > 使用自定义公式进行 VBA 验证 - 字符串变量中的公式问题

问题描述

我正在为 for 循环中的单元格范围进行数据验证。我已经在我的 for 循环中应用了其他验证,它们工作正常,但是当我想使用自定义公式COUNTIF来检查唯一值时,我在互联网上找到了很多示例和教程,但出现错误:

运行时错误 1004:指向行的应用程序定义或对象定义错误

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

功能有什么问题COUNTIF?对于指定的行,此验证规则仅在 for 循环中调用一次。下面的代码:

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>

我还尝试在使用 excel 界面并使用自动生成的代码作为模板时记录宏,但是当我将其复制到 for 循环中时,我也收到此错误,原始 Formula1 字符串如下:

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

LICZ.JEŻELI 是 COUNTIF 的本地版本。

但无论如何我仍然得到同样的错误。我该如何解决这个问题?

标签: excelvba

解决方案


推荐阅读