[英]Excel VBA SUMIF across multiple sheets
我正在編寫一個函數來總結 1 整個月每天的飛行時間。
我嘗試了 2 種方案 - 返回一個字符串,該字符串將用公式填充單元格。 嘗試返回單元格的值。 我認為第二個是首選。 函數應該返回 var 或 string。 我所有的嘗試都在分配返回值的行上拋出了錯誤。
Option Explicit
Function HoursFlown() As String
'writes formula for cells d10:d14 to calculate hours flown
'checks across all worksheets (each day of month) confirms pilot
'and a flight exists and sums "flight hours totals" for toatal hours in month to date.
'!!!At present this is not a function so does not return a result and takes no arguments.
Application.Volatile
Dim WS_Count As Integer
Dim I As Integer
Dim strTabs As String
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For I = 2 To WS_Count
' Insert your code here.
'strTabs = strTabs & " " & ActiveWorkbook.Worksheets(I).Name
strTabs = strTabs & "(SUMIF('" & ActiveWorkbook.Worksheets(I).Name & "'!L3:L4,c10,'" & ActiveWorkbook.Worksheets(I).Name & "'!M3:M4)+"
' The following line shows how to reference a sheet within
' the loop by displaying the worksheet name in a dialog box.
'MsgBox ActiveWorkbook.Worksheets(I).Name
'MsgBox strTabs
Next I
strTabs = "=" & (Left(strTabs, Len(strTabs) - 1)) & "))"
'Range("J19").Formula = MsgBox(strTabs) '<-- this is working (it doesn't throw an error but it doesn't return the correct results)
'Range("J19").Value = strTabs
'Range("J20").Formula = strTabs 'this line throws object-defined error
HoursFlown = strTabs
End Function
嘗試使用 Application.SumIf 代替...
Function HoursFlown() As Double
'writes formula for cells d10:d14 to calculate hours flown
'checks across all worksheets (each day of month) confirms pilot
'and a flight exists and sums "flight hours totals" for toatal hours in month to date.
'!!!At present this is not a function so does not return a result and takes no arguments.
Application.Volatile
Dim WS_Count As Integer
Dim I As Integer
Dim total As Double
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
total = 0
For I = 2 To WS_Count
total = total + Application.SumIf(ActiveWorkbook.Worksheets(I).Range("L3:L4"), Range("c10").Value, ActiveWorkbook.Worksheets(I).Range("M3:M4"))
Next I
HoursFlown = total
End Function
編輯
對於智能感知,您可以參考 WorksheetFunction 對象的 SumIf 成員(即 WorksheetFunction.SumIf(...))。 但是,在這種情況下,如果它返回錯誤,您將收到一個破壞性錯誤,您需要處理該錯誤。
但是,使用 Application.SumIf,如果返回錯誤,您將得到一個非破壞性錯誤,您可以使用 IsError 函數對其進行測試...
Dim total as Variant 'declared as Variant in case SumIf returns an error
total = Application.SumIf(.....)
If Not IsError(total) Then
'do something
Else
'do something else
End If
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.