excel - 如何插入条件 "if it contains"以在 VBA 中搜索特定字母?

标签 excel vba filter count conditional-statements

我想计算参数 CA、CU 和 CH 在如下所示的 excel 中出现了多少次:

enter image description here

我尝试使用以下代码,但由于单元格不仅包含我正在搜索的参数,因此它不起作用:

Sub ContarOV()

    Dim cont As Variant
    Dim sumaCA As Variant
    Dim sumaCU As Variant
    Dim sumaCH As Variant

    sumaCA = 0
    sumaCU = 0
    sumaCH = 0

    For cont = 3 To 12
        If Cells(cont, 2) = ("CA") Then
            sumaCA = sumaCA + 1
        End If
        If Cells(cont, 2) = ("CU") Then
             sumaCU = sumaCU + 1
        End If
        If Cells(cont, 2) = ("CH") Then
            sumaCH = sumaCH + 1
        End If
    Next cont

End Sub

最佳答案

根据@BigBen,我会尽量避免任何迭代。以下选项之一怎么样(假设您的数据来自 A2:A? ):

Sub Test()

Dim lr As Long, x As Long
Dim arr As Variant
Dim rng As Range

With Sheet1 'Change according to your sheets CodeName

    'Get last used row
    lr = .Cells(.Rows.Count, 1).End(xlUp).Row

    'Get data into memory for method 1
    arr = Application.Transpose(.Range("A2:A" & lr).Value)

    'Create range object for method 2
    Set rng = .Range("A2:A" & lr)

    'Method 1: Count values with FILTER
    Debug.Print UBound(Filter(arr, "CA")) + 1
    Debug.Print UBound(Filter(arr, "CU")) + 1
    Debug.Print UBound(Filter(arr, "CH")) + 1

    'Method 2: Count values with COUNTIF
    Debug.Print WorksheetFunction.CountIf(rng, "CA*")
    Debug.Print WorksheetFunction.CountIf(rng, "CU*")
    Debug.Print WorksheetFunction.CountIf(rng, "CH*")

End With

End Sub

顺便说一句,我会给 sumaCA和你的其他变量一个有意义的数据类型,Long在这种情况下。

关于excel - 如何插入条件 "if it contains"以在 VBA 中搜索特定字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564772/

相关文章:

excel - Google Sheets 仅评估 SUMIFS 语句中数组中的第一个条件

php - 通过php导出到excel文件时如何保持mysql数据的格式

mysql - 比较多个模式

filter - ZF2 : How do I implement a custom filter?

excel - 在 Excel VBA 中循环字符串列表

java - 设置行中每个表格单元格的颜色

excel - 使用可变标准 VBA 进行自动过滤

php - 如何避免在 PHPExcel 中丢失宏?

c - 这个过滤器实现是否产生正确的输出?

jQuery:通过类过滤掉元素?