通过单元格列表数据验证来计算单元格中以逗号分隔的各个值

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

在我的工作表的 E 列中,我有一个单元格下拉列表数据验证,其中包含选项(CAIOS、ERCOT、MISO、PJM、SPP)。我编写了一个 VBA 来允许在每个单元格中进行多项选择。我有单元格 [PJM]、[PJM]、[PJM]、[PJM]、[PJM、SPP]。我正在尝试计算细胞是否含有 PJM。我使用通配符,但结果始终是 4 而不是 5。

excel vba countif
1个回答
0
投票

针对您的情况尝试此操作:

Function CountPJMOccurrences(cellValue As String) As Long
Dim selections() As String
Dim i As Long
Dim countPJM As Long

' Split cell contents based on comma
selections = Split(cellValue, ",")

' Loop through the array and count occurrences of "PJM"
For i = LBound(selections) To UBound(selections)
    If Trim(selections(i)) = "PJM" Then
        countPJM = countPJM + 1
    End If
Next i

CountPJMOccurrences = countPJM

结束功能

您可以在工作表中使用此功能,例如,如果您的下拉列表单元格位于单元格 E1 中,则可以在 F1 中输入以下公式 =PJMO 发生次数(E1)

© www.soinside.com 2019 - 2024. All rights reserved.