我正在尝试在VBA代码中使用这个公式 =AND(COUNTIF(A2;"*"&$C$2:$C$5&"*")) 但出现错误 13

问题描述 投票:0回答:1

目标是检查 C 列列表中的所有名称是否都在 a 列的单元格中。
结果应该是 true 或 false。
它适用于工作表中的公式,但不适用于我创建的示例 VBA 代码。
b 列中公式的结果为:

FALSE   
FALSE   
TRUE   
FALSE   

,因为第三行 a 列包含 c 列列表中的所有名称(以及更多名称)。

我将其转换为如下所示:

Sub CI()
Cells(7, 2) =  
Application.WorksheetFunction.And(Application.WorksheetFunction.CountIf(Cells(2, 1),  "*" & Range("C2:C5") & "*"))
End Sub
A 栏 B 栏 c 栏
名字 在列表中 列表
科尼·吉安卡洛
=AND(COUNTIF(A2;"*"&$C$2:$C$5&"*"))
奥努尔
=AND(COUNTIF(A3;"*"&$C$2:$C$5&"*"))
吉安卡洛
科尼·吉安卡洛·马辛·奥努尔
=AND(COUNTIF(A4;"*"&$C$2:$C$5&"*"))
马辛
吉安卡洛·马尔辛
=AND(COUNTIF(A5;"*"&$C$2:$C$5&"*"))

非常感谢任何帮助。 :-)

excel vba countif
1个回答
0
投票

我会创建一个自定义函数并从单元格中调用。如您所知,将绝对范围($)放入列表范围,如下例所示。 在单元格 B2 处:=isAllNamesInRange(A2,$C$2:$C$4)

如果在“名称”范围内找到“列表”中的所有名称,则

isAllNamesInRange 函数返回 True,否则返回 False

Public Function isAllNamesInRange(names As Range, list As Range) As Boolean
    Dim name As Range
    Dim flag As Boolean
    
    ' Initialize the result variable as True
    isAllNamesInRange = True
    
    ' Loop through each cell in the 'list' range
    For Each name In list
        ' Check if the current 'name' cell's value is found within the 'names' range
        If InStr(names, name) > 0 Then
            ' If found, set the 'flag' to True
            flag = True
        Else
            ' If not found, set the 'flag' to False
            flag = False
        End If
        
        ' Update the result by multiplying it with the 'flag'
        ' If any 'flag' is False, 'isAllNamesInRange' will become False
        isAllNamesInRange = isAllNamesInRange * flag
    Next name
    
End Function
© www.soinside.com 2019 - 2024. All rights reserved.