0

我知道我没有正确执行此操作,但我是 VBA 初学者,并且正在尝试在工作簿中的多个工作表上执行值的 sumif,然后返回这些 sumif 的总和。

这就是我尝试的方式,但我得到了#NAME?错误,不知道从这里去哪里。

Public Function Lookup(x As Long) As Long

Dim sh As Worksheet, wb As Workbook, arr() As Variant

Set wb = Workbooks.Open("Purchased.xlsm")

For Each sh In wb
    arr() = Application.SumIf(Range("A1:A10000"), x, Range("B1:B10000"))
Next

Lookup = Application.WorksheetFunction.Sum(arr())

End Function

我一直无法让这个工作,它返回一个#VALUE!错误,但我认为这可能更接近我需要的:

Public Function AddItUp(x As Long) As Long
Dim sh As Worksheet, wb As Workbook, RunningSum() As Variant
Dim i As Long, j As Long
Set wb = Workbooks.Open("Week1Input.xlsm")
j = wb.Worksheets.Count
ReDim RunningSum(1 To j)
For i = 1 To j
    RunningSum(i) = Application.SumIf(wb.sh(i).Range("A1:A10"), x, wb.sh(i).Range("B1:B10"))
Next i
AddItUp = Application.WorksheetFunction.Sum(RunningSum)
End Function
4

2 回答 2

1

您不能为空数组赋值。将 更改为arr()可以保存该值的东西。此外,查找是 excel 中的内置函数名称,它会使 excel(和其他用户)感到困惑

Public Function AddItUp(x As Long) As Long
Dim sh As Worksheet, wb As Workbook, RunningSum As Variant
Set wb = Workbooks.Open("Purchased.xlsm")
RunningSum=0
For Each sh In wb
    RunningSum = RunningSum + _
        Application.SumIf(Range("A1:A10000"), x, Range("B1:B10000"))
    'line broken for readability
Next
AddItUp = RunningSum
End Function
于 2013-09-17T20:10:41.930 回答
0

我最终只是合并了工作簿,因为这是我可以让它工作的唯一方法:

Public Function AddItUp(x As Long) As Long
Dim RunningSum() As Variant
Dim i As Long, j As Long
j = ActiveWorkbook.Worksheets.Count
ReDim RunningSum(3 To j)
For i = 3 To j
    RunningSum(i) = Application.SumIf(Worksheets(i).Range("A1:A10000"), x, Worksheets(i).Range("B1:B10000"))
Next i
AddItUp = Application.WorksheetFunction.Sum(RunningSum)
End Function
于 2013-09-19T19:43:05.503 回答