[英]how can I insert a condition "if it contains" to search for a specific letter in VBA?
I want to count how many times appear the parameters CA, CU and CH, in an excel that looks like this:我想计算参数 CA、CU 和 CH 在如下所示的 excel 中出现的次数:
I have tried to use the following code, but as the cells don't contain only the parameter I am searching for, it doesn't work:我尝试使用以下代码,但由于单元格不只包含我正在搜索的参数,因此它不起作用:
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
As per @BigBen, I would try to avoid any iteration.根据@BigBen,我会尽量避免任何迭代。 What about one of the following options (assuming your data sits from
A2:A?
):以下选项之一怎么样(假设您的数据来自
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
Btw, I would give sumaCA
and your other variables a meaningfull data type, Long
in this case.顺便说一句,在这种情况下,我会给
sumaCA
和您的其他变量一个有意义的数据类型, Long
。
You can use InStr()
to return the position of the desired characters in the string.您可以使用
InStr()
返回字符串中所需字符的位置。 This would look something like If Not InStr(1, Cells(cont,2).Text, "CH") = 0 Then
, but looping through strings is generally a slow process.这看起来像
If Not InStr(1, Cells(cont,2).Text, "CH") = 0 Then
,但遍历字符串通常是一个缓慢的过程。 Unless you have a specific need for looping, I like BigBen's answer a lot better than I like looping with InStr()
.除非您有特定的循环需求,否则我更喜欢 BigBen 的答案,而不是使用
InStr()
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.