arrays - VBA - Countif Range 与数组中的至少一个值匹配

标签 arrays vba excel match

我不知道如何完成这个任务。如果该范围内的单元格中至少有一个单词与数组匹配,我需要计算工作表中的范围。例如,如果单元格 "B2" 有一个句子,其中包含数组中的单词之一,则计为 1,如果与某个范围匹配,则简单地 countif 为一个范围大批。我的代码会更好地显示我的问题,所以如果这令人困惑,我深表歉意。

With ThisWorkbook
    Dim Keywords As Variant
    Dim iVal As Double
    keyword = Array("*cold*", "*hot*", "*warm*", "*cool*", _
        "*temp*", "*thermostat*", "*heat*", "*temperature*", _
        "*not working*", "*see above*", "*broken*", "*freezing*", _
        "*warmer*", "*air conditioning*", "*humidity*", _
        "*humid*")
    iVal=Application.WorksheetFunction.CountIf(Range("B2",Range("B2").End(xlDown)),keyword)

    Dim rep As Worksheet
    Set rep = Worksheets("Report")
    rep.Range("A1") = iVal
End With

正如我所展示的,如果数组中的这些单词之一与定义范围内的单元格匹配,Range("B2", Range("B2").End(xlDown)),然后在 Worksheets("Report").Range("A1") 中计数并显示值。感谢您的任何帮助,谢谢。

最佳答案

您需要比较两个列表中的值 - 您的 RangeArray。最简单的方法是通过嵌套循环。像这样:

Sub TestMe()

    With ThisWorkbook

        Dim Keywords    As Variant
        Dim iVal        As Long
        Dim myRange     As Range
        Dim myCell      As Range
        Dim bCount      As Boolean
        Dim myVal       As Variant

        keyword = Array("cold", "hot", "warm", "cool", _
                        "temp", "thermostat", "heat", "temperature", _
                        "not working", "see above", "broken", "freezing", _
                        "warmer", "air conditioning", "humidity", _
                        "humid")

        Set myRange = Columns(2).SpecialCells(2)

        For Each myCell In myRange
            bCount = False

            For Each myVal In keyword
                If InStr(1, myCell, myVal, vbTextCompare) Then bCount = True
            Next myVal

            If bCount Then iVal = iVal + 1                
        Next myCell

        Debug.Print iVal
    End With

End Sub

每当标志 bCount 设置为 True 时,计数就会完成。外循环的每次迭代都会将其重置为 False。 我会删除 *,因为我使用 InStr() 进行检查,而星星在那里有点无用。

此外Columns(2).SpecialCells(2)返回一个范围,仅包含值,这些值在B列中是非公式且非空的。

关于arrays - VBA - Countif Range 与数组中的至少一个值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535753/

相关文章:

excel - VBA 使用单元格引用激活单元格

excel - vba:日期函数返回 "00:00:00"

python - 从 xlwings 返回值到 vba

excel - 在 VBA ArrayList 中搜索元素

php - 如何在 PHP 和 MySQL 中正确获取欧元符号

sql - Now() 在 ODBC SQL 查询中?

javascript - Vue JS显示所选数组的内容

arrays - JSON Schema Array 必须包含特定的字符串

arrays - 将 MonadRandom 与堆栈中的 ST 计算相结合

c++ - 使用数组并移动重复项以结束