我一直在尝试编写函数来自动执行一些常规计算。
但是我遇到了以下问题:
SumbyCode1
函数始终适用于包含数据的工作表。但是,它在同一工作簿的其他工作表中不起作用。CountbyCode
功能不起作用。我试过这个函数作为一个普通的子,它在那里工作得很好。但是,我在函数中应用代码。它根本不起作用。请参阅以下代码:
Public Function SumbyCode1(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)
Dim var()
var = Array(wirecode0, wirecode1, wirecode2, wirecode3, wirecode4, _
wirecode5, wirecode6, wirecode7, wirecode8)
Dim ws As Worksheet
Set ws = Worksheets("Banking Transaction")
Dim colnumbercode As Integer
Dim colnumberamount As Integer
Dim total As Variant
total = 0
With ws
colnumbercode = Application.WorksheetFunction.Match("Type", Range("1:1"), 0)
colnumbercodeletter = Chr(64 + colnumbercode)
codecol = colnumbercodeletter & ":" & colnumbercodeletter
colnumberamount = Application.WorksheetFunction.Match("Amount", Range("1:1"), 0)
colnumberamountletter = Chr(64 + colnumberamount)
codeamount = colnumberamountletter & ":" & colnumberamountletter
For i = 0 To 8
total = Application.WorksheetFunction.SumIf(Range(codecol), _
var(i), Range(codeamount)) + total
Next i
End With
SumbyCode1 = total
End Function
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)
Dim var()
var = Array(wirecode0, wirecode1, wirecode2, wirecode3, _
wirecode4, wirecode5, wirecode6, wirecode7, wirecode8)
Dim ws As Worksheet
Set ws = Worksheets("Banking Transaction")
Dim colnumbercode As Integer
Dim total As Variant
total = 0
With ws
colnumbercode = Application.WorksheetFunction.Match("Type", Range("1:1"), 0)
colnumbercodeletter = Chr(64 + colnumbercode)
codecol = colnumbercodeletter & ":" & colnumbercodeletter
For i = 0 To 8
total = Application.WorksheetFunction.CountIf(Range(codecol), _
var(i)) + total
Next i
End With
CountbyCode = total
End Function
答案 0 :(得分:2)
您需要完全限定参考资格。当你使用:
total = Application.WorksheetFunction.CountIf(Range(codecol), var(i)) + total
VB编辑器默默地将Range(codecol)
解释为ThisWorkbook.ActiveSheet.Range(codecol)
,这意味着该函数仅适用于当前活动的工作表。正如@ScottCraner建议的那样,您需要使用之前的With ws
声明将其更改为完全明确的引用,方法是将Range(codecol)
更改为.Range(codecol)
。