我一直在编写一个按交易代码计算银行交易的功能。但是,countif函数在VBA函数中不起作用。然而,当我运行相同的代码集作为独立的子代码时,函数会起作用并返回正确的值。
我一直在尝试不同的方法来解决这个公式,但我仍然很困惑为什么CountIf在这里不起作用。
非常感谢你。 以下是代码:
Sub Test()
' Input Transaction Code
wirecode0 = InputBox("code1")
wirecode1 = InputBox("code2")
' Pass codes to array
Dim var()
var = Array(wirecode0, wirecode1, wirecode2, wirecode3, _
wirecode4, wirecode5, wirecode6, wirecode7, wirecode8)
' Define worksheet and variables
Dim ws As Worksheet
Set ws = Worksheets("Banking Transaction")
Dim colnumbercode As Integer
Dim totalcount As Integer
'Locate the column "Type" which contains the transaction codes
With ws
colnumbercode = Application.WorksheetFunction.Match("Type", .Range("1:1"), 0)
colnumbercodeletter = Chr(64 + colnumbercode)
codecol = colnumbercodeletter & ":" & colnumbercodeletter
'Count codes
For i = 0 To 8
If var(i) = "" Then
var(i) = 0
End If
totalcount = Application.WorksheetFunction.CountIf(.Range(codecol), var(i)) + totalcount
Next i
End With
MsgBox (totalcount)
End Sub
Public Function CountbyCode(ByRef wirecode0, Optional ByRef wirecode1, _
Optional ByRef wirecode2, Optional ByRef wirecode3, _
Optional ByRef wirecode4, Optional ByRef wirecode5, _
Optional ByRef wirecode6, Optional ByRef wirecode7, _
Optional ByRef wirecode8)
' Pass codes to array
Dim var()
var = Array(wirecode0, wirecode1, wirecode2, wirecode3, _
wirecode4, wirecode5, wirecode6, wirecode7, wirecode8)
' Define worksheet and variables
Dim ws As Worksheet
Set ws = Worksheets("Banking Transaction")
Dim colnumbercode As Integer
Dim totalcount As Integer
'Locate the column "Type" which contains the transaction codes
With ws
colnumbercode = Application.WorksheetFunction.Match("Type", .Range("1:1"), 0)
colnumbercodeletter = Chr(64 + colnumbercode)
codecol = colnumbercodeletter & ":" & colnumbercodeletter
'Count codes
For i = 0 To 8
If var(i) = "" Then
var(i) = 0
End If
totalcount = Application.WorksheetFunction.CountIf(.Range(codecol), var(i)) + totalcount
Next i
End With
CountbyCode = totalcount
End Function
答案 0 :(得分:0)
如果您没有建议wirecode1
,wirecode2
(等)的值,则会为其分配值Missing
(注意:不是"Missing"
)。
无法将Missing
与""
进行比较(或以其他方式将其视为String
),而不会产生错误。
我建议您更改循环以测试缺失值:
For i = 0 To 8
If Not IsMissing(var(i)) Then
If var(i) = "" Then
var(i) = 0
End If
totalcount = Application.WorksheetFunction.CountIf(.Range(codecol), var(i)) + totalcount
End If
Next i
另请注意,您无需计算codecol
- 您可以使用.Columns(colnumbercode)
代替.Range(codecol)
。