我想循环遍历一组列,从而计算值“PAS”或“VRIJ”出现的次数。
因此我写了以下代码:
Sub CountWorkDays()
Dim count As Integer
count = 0
For i = 1 To 6
Dim var1 As Characters
var1 = Cells(1, i).Value
If var1 = "Test" Then
count = count + 1
ElseIf var1 = "PAS" Then
count = count + 1
End If
Next
End
MsgBox (count)
End Sub
但是当我运行代码时,我收到以下错误:
Run-time error '91':
Object-variable or with block variable is not set
尝试使用Google搜索错误,但无法找到它来自哪里。关于如何改进上述代码的任何想法?
答案 0 :(得分:1)
您已将var1设置为字符 - 将其设置为字符串,然后将DIM线移到循环外部并删除END语句 - 代码执行将停止。
Sub CountWorkDays()
Dim var1 As String
Dim count As Integer
count = 0
For i = 1 To 6
var1 = Cells(1, i).Value
If var1 = "Test" Then
count = count + 1
ElseIf var1 = "PAS" Then
count = count + 1
End If
Next i
MsgBox (count)
End Sub
编辑:
这可能是一种更好的方法:
Sub CountWorkDays()
MsgBox Application.WorksheetFunction.CountIf(Range("A1:A6"), "Test") + _
Application.WorksheetFunction.CountIf(Range("A1:A6"), "PAS")
End Sub