如何使用COUNTIF()
函数仅计算范围内存在的某些文本字符串?
我尝试使用下面的内容,但是我收到错误
Syntax error
这是我尝试的语法
Dim worksheetmaster As String = "Master"
Dim worksheettocheck As String = "New"
Dim softcount As Int, i As Long, hardcount As Int
softcount = Evaluate("=COUNTIF(Range('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Soft")")
hardcount = Evaluate("=COUNTIF(Range('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Hard")")
修改
我尝试在没有Range
的情况下使用此语法,但仍然出现错误
hardcount = Evaluate("=COUNTIF('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Hard"")
答案 0 :(得分:1)
要将A
列与Hard
列中的B
匹配,应该是这样的:
hardcount = Application.Evaluate("COUNTIFS('" & worksheettocheck & "'!A:A,'" & worksheetmaster & "'!A" & i & ",'" & worksheettocheck & "'!B:B, ""Hard"")")
softcount = Application.Evaluate("COUNTIFS('" & worksheettocheck & "'!A:A,'" & worksheetmaster & "'!A" & i & ",'" & worksheettocheck & "'!B:B, ""Soft"")")
答案 1 :(得分:0)
您的第一个语法错误在这里:
Dim worksheetmaster As String = "Master"
Dim worksheettocheck As String = "New"
你不能这样做。相反,您需要使用:
Dim worksheetmaster As String
Dim worksheettocheck As String
worksheetmaster = "Master"
worksheettocheck = "New"
更好的方法是将它们分配到工作表中,但让我们尽可能地使用您的代码,而不是完全重写它。
对于countif,您不能以这种方式加入范围。您甚至没有为i分配值,但假设i = 1,您的代码:
softcount = Evaluate("=COUNTIF(Range('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Soft")")
评估VBA中的总废话:
softcount = Evaluate(=COUNTIF(Range('New'!A:A'Master'!A1)Soft))
现在,从我所知道的,你要做的是计算单元格Master中的值的多少倍!A&我出现在New!A:A的范围内,取决于Master!A& I ="软"或者大师!A& I ="硬盘&#34 ;.因此,让我们看看我们是否能找到能够做到这一点的代码。
对于我们输入的数据" Soft"进入大师!A1和"硬"进入师父!A2。然后我们输入随机" Soft"或"硬"在New!A:A。
栏中的各个单元格中现在您的代码如下所示:
Dim worksheetmaster As String
Dim worksheettocheck As String
Dim softcount As Long, i As Long, hardcount As Long
worksheetmaster = "Master"
worksheettocheck = "New"
i = 1
softcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("A" & i).Value)
i = 2
hardcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("A" & i).Value)
效率低且有限,但它保留了尽可能多的原始代码,并且有效。
编辑添加:if" Hard"是在大师!B&我而不是A&我然后代码变成:
i = 1
softcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("A" & i).Value)
hardcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("B" & i).Value)