VBA函数只能在一个工作表中使用

我一直在努力编写函数来自动执行一些常规计算。
不过,我遇到了以下问题:

  1. SumbyCode1函数总是在包含数据的工作表中工作。 但是,在同一工作簿的其他工作表中不起作用。
  2. CountbyCode函数不起作用。 我尝试了一个普通的子函数,它在那里完美的工作。 然而,那么我在function上应用代码。 它根本不起作用。

看到下面的代码:

 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 

您需要完全符合您的参考资格。 当你使用:

total = Application.WorksheetFunction.CountIf(Range(codecol), var(i)) + total

VB编辑器默认将Range(codecol)解释为ThisWorkbook.ActiveSheet.Range(codecol) ,这意味着该函数只对当前活动的工作表起作用。 正如@ScottCraner所build议的那样,您需要通过将Range(codecol)更改为.Range(codecol)来将其更改为完全明确的引用。