Excel VBA SUMIF на нескольких листах - PullRequest
0 голосов
/ 19 января 2020

Я пишу функцию для суммирования летных часов каждого дня за 1 целый месяц.

Я пробовал 2 сценария ios - возвращает строку, которая заполняет ячейку формулой. Попытайтесь вернуть значение для ячейки. Второе, я полагаю, предпочтительнее. Функция должна возвращать либо 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

1 Ответ

0 голосов
/ 19 января 2020

Попробуйте вместо этого использовать 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

EDIT

Для IntelliSense вы можете обратиться к члену SumIf объекта WorksheetFunction ( ie. 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

Надеюсь, это поможет!

...