|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
VB-自定义函数
实现满足要求的字符计数
条件1是IPHONE 12 BLACK,条件2是64GB,范围里IPHONE 12 64GB BLACK是满足的要计数,范围里IPHONE 12 MINI 64GB BLACK是不满足的,不用计数。
函数过程:
Function COUNT_MATCHES(rng As Range, cond1 As String, cond2 As String) As Long
Dim arr1() As String, arr2() As String
Dim i As Long, j As Long, count As Long
'将条件1和条件2拆分为数列
arr1 = Split(cond1, " ")
arr2 = Split(cond2, " ")
'循环遍历范围值
For i = 1 To rng.Cells.Count
Dim tempArr() As String
tempArr = Split(rng.Cells(i).Value, " ")
Dim cond1Found As Boolean
cond1Found = False
Dim cond2Found As Boolean
cond2Found = False
'检查范围值是否包含所有条件1和条件2的值
For j = 0 To UBound(arr1)
If InStr(1, rng.Cells(i).Value, arr1(j), vbTextCompare) > 0 Then
cond1Found = True
Else
cond1Found = False
Exit For
End If
Next j
For j = 0 To UBound(arr2)
If InStr(1, rng.Cells(i).Value, arr2(j), vbTextCompare) > 0 Then
cond2Found = True
Else
cond2Found = False
Exit For
End If
Next j
'如果范围值包含所有条件1和条件2的值,并且不包含额外的值,则计数
If cond1Found And cond2Found And UBound(tempArr) = UBound(arr1) + UBound(arr2) + 1 Then
count = count + 1
End If
Next i
COUNT_MATCHES = count
End Function
|
|