VBA – Countif范围至less匹配数组中的一个值

我不知道如何完成这个任务。 如果至less有一个单元格中的单词与数组匹配,我需要在表单中计算一个范围。 例如,如果单元格"B2"有一个句子,其中一个单词在数组中,那么这个单词就算作一个单词,如果它与一个数组相匹配,就简单地确定一个范围。 我的代码将更好地显示我的问题,所以我很抱歉,如果这一切混淆。

 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))内的单元格中匹配, Range("B2", Range("B2").End(xlDown)) ,然后计算并显示Worksheets("Report").Range("A1")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中是非公式和非空的值。

这是我的回答,就像@Vityata一样。 请注意,您可以使用他的SpecialCells的build议来读取数组中的范围时忽略空白。

注意,如果这是数组中的内容,它会查找"*Cold*" 。 把简单的"Cold"等,在数组中,如果这是在单元格内被查找的单词。

 Option Explicit Public Sub test() Dim Keywords As Variant Dim iVal As Long Dim wb As Workbook Dim ws As Worksheet Set wb = ThisWorkbook Set ws = wb.Sheets(2) Keywords = Array("*cold*", "*hot*", "*warm*", "*cool*", _ "*temp*", "*thermostat*", "*heat*", "*temperature*", _ "*not working*", "*see above*", "*broken*", "*freezing*", _ "*warmer*", "*air conditioning*", "*humidity*", _ "*humid*") With ws Dim rangetoCheck() Dim counter1 As Long Dim counter2 As Long Dim totalCount As Long iVal = 0 rangetoCheck = .Range("B2", .Range("B2").End(xlDown)).value For counter1 = LBound(rangetoCheck, 1) To UBound(rangetoCheck, 1) For counter2 = LBound(Keywords) To UBound(Keywords) If InStr(1, rangetoCheck(counter1, 1), Keywords(counter2), vbBinaryCompare) Then iVal = iVal + 1 Exit For End If Next counter2 Next counter1 End With MsgBox iVal End Sub