Vba excel среднее значение

In this Article

  • AVERAGE WorksheetFunction
  • Assign AVERAGE Result to a Variable
  • AVERAGE with a Range Object
  • AVERAGE Multiple Range Objects
  • Using AVERAGEA
  • Using AVERAGEIF
  • Disadvantages of WorksheetFunction
    • Using the Formula Method
    • Using the FormulaR1C1 Method

This tutorial will demonstrate how to use the Excel Average function in VBA.

The Excel AVERAGE Function is used to calculate an average from a range cells in your Worksheet that have values in them. In VBA, It is accessed using the WorksheetFunction method.

AVERAGE WorksheetFunction

The WorksheetFunction object can be used to call most of the Excel functions that are available within the Insert Function dialog box in Excel. The AVERAGE function is one of them.

Sub TestFunction
  Range("D33") = Application.WorksheetFunction.Average("D1:D32")
End Sub

vba average syntax

You are able to have up to 30 arguments in the AVERAGE  function. Each of the arguments must refer to a range of cells.

This example below will produce the average of the sum of the cells B11 to N11

Sub TestAverage()
   Range("O11") = Application.WorksheetFunction.Average(Range("B11:N11"))
End Sub

The example below will produce an average of the sum of the cells in B11 to N11 and the sum of the cells in B12:N12. If you do not type the Application object, it will be assumed.

Sub TestAverage()
  Range("O11") = WorksheetFunction.Average(Range("B11:N11"),Range("B12:N12")) 
End Sub

Assign AVERAGE Result to a Variable

You may want to use the result of your formula elsewhere in code rather than writing it directly back to an Excel Range. If this is the case, you can assign the result to a variable to use later in your code.

Sub AssignAverage()
   Dim result As Integer
'Assign the variable   
   result = WorksheetFunction.Average(Range("A10:N10"))
'Show the result
   MsgBox "The average for the cells in this range is " & result
End Sub

vba average msgbox

AVERAGE with a Range Object

You can assign a group of cells to the Range object, and then use that Range object with the WorksheetFunction object.

Sub TestAverageRange()
   Dim rng As Range
'assign the range of cells
   Set rng = Range("G2:G7")
'use the range in the  formula
   Range("G8") = WorksheetFunction.Average(rng)
'release the range object
  Set rng = Nothing
End Sub

AVERAGE Multiple Range Objects

Similarly, you can calculate the average of the cells from multiple Range Objects.

Sub TestAverageMultipleRanges() 
   Dim rngA As Range 
   Dim rngB as Range
'assign the range of cells 
   Set rngA = Range("D2:D10") 
   Set rngB = Range("E2:E10")   
'use the range in the formula 
Range("E11") = WorksheetFunction.Average(rngA, rngB)
 'release the range object
  Set rngA = Nothing 
  Set rngB = Nothing
End Sub

Using AVERAGEA

The AVERAGEA Function differs from the AVERAGE function in that it create an average from all the cells in a range, even if one of the cells has text in it – it replaces the text with a zero and includes that in calculating the average.   The AVERAGE function would ignore that cell and not factor it into the calculation.

Sub TestAverageA()
   Range("B8) = Application.WorksheetFunction.AverageA(Range("A10:A11")) 
End Sub

In the example below, the AVERAGE function returns a different value to the AVERAGEA function when the calculation is used on cells A10 to A11

vba average averagea

The answer for the AVERAGEA formula is lower than the AVERAGE formula as it replaces the text in A11 with a zero, and therefore averages over 13 values rather than the 12 values that the AVERAGE is calculating over.

Using AVERAGEIF

The AVERAGEIF Function allows you to average the sum of a range of cells that meet a certain criteria.

Sub AverageIf()
   Range("F31") = WorksheetFunction.AverageIf(Range("F5:F30"), "Savings", Range("G5:G30"))
End Sub

The procedure above will only average the cells in range G5:G30 where the corresponding cell in column F has the word ‘Savings’ in it.  The criteria you use has to be in quotation marks.

vba average average if

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Disadvantages of WorksheetFunction

When you use the WorksheetFunction to average the values in a range in your worksheet, a static value is returned, not a flexible formula. This means that when your figures in Excel change, the value that has been returned by the WorksheetFunction will not change.

vba average static

In the example above, the procedure TestAverage procedure has created the average of B11:M11 and put the answer in N11.   As you can see in the formula bar, this result is a figure and not a formula.

If any of the values change therefore in the Range(B11:M11 ), the results in N11 will NOT change.

Instead of using the WorksheetFunction.Average, you can use VBA to apply the AVERAGE Function to a cell using the Formula or FormulaR1C1 methods.

Using the Formula Method

The formula method allows you to point specifically to a range of cells eg: B11:M11 as shown below.

Sub TestAverageFormula()
  Range("N11").Formula = "=Average(B11:M11)"
End Sub

vba average formula

Using the FormulaR1C1 Method

The FomulaR1C1 method is more flexible in that it does not restrict you to a set range of cells. The example below will give us the same answer as the one above.

Sub TestAverageFormula()
   Range("N11").Formula = "=Average(RC[-12]:RC[-1])"
End Sub

vba average formula r1c1

However, to make the formula more flexible, we could amend the code to look like this:

Sub TestAverageFormula() 
   ActiveCell.FormulaR1C1 = "=Average(R[-11]C:R[-1]C)" 
End Sub

Wherever you are in your worksheet, the formula will then average the values in the 12 cells directly to the left of it and place the answer into your ActiveCell. The Range inside the AVERAGE function has to be referred to using the Row (R) and Column (C) syntax.

Both these methods enable you to use Dynamic Excel formulas within VBA.

There will now be a formula in N11 instead of a value.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    VBA (Visual Basic for Applications) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft.

    With Excel VBA, one can automate many tasks in excel and all other office softwares. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions.
    Let’s see Average functions in Excel.

    1. AVERAGE It returns the arithmetic mean of all of its arguments.
      Syntax:
      =AVERAGE(number1, number2, …)

      Here,
      number 1: This is the first number in your cell. You can specify it upto 255 numbers.
      number 2: This is an Optional field. You can specify it upto 255 numbers.

      Example:
      average

      Output:
      output

    2. AVERAGEIF: It calculates the average of only those values which meet a certain criteria.

      Syntax:

      =AVERAGEIF(range, criteria, average_range)

      range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered.

      criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35”

      average_range: [Optional] If this is not mentioned, Excel will get average of only those cells on which criteria is applied, which are specified in the range argument.

      Notes:
      -> If a cell in average_range is an empty cell, it will be ignored.
      -> If range is a text value or blank, it will return an error.
      -> If a cell in criteria is empty, it will be considered as 0 value.
      -> If no cell meets the criteria, it will return an error.

      Example:
      averageif

      Output:
      out

    3. AVERAGEIFS: Calculate average of cells that meet multiple criteria.
      Syntax:
      =AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2], …)

      average_range: (Required) One or more cells to calculate average.

      criteria_range1: (Required) 1 to 127 ranges to evaluate the given criteria.

      criteria1: 1 to 127 criteria in the form of numbers, expression to be averaged. This defines which all cells in criteria_range1 are to be averaged. For instance, criteria can be like this, “>32”, “apple”, “D7”

      Example:
      averageifs

      Output:
      out

    Like Article

    Save Article

    In Excel, you can use VBA to calculate the average values from a range of cells or multiple ranges. And, in this tutorial, we are going to learn the different ways that we can use it.

    Average in VBA using WorksheetFunction

    In VBA, there are multiple functions that you can use, but there’s no specific function for this purpose. That does not mean we can’t do an average. In VBA, there’s a property called WorksheetFunction that can help you to call functions into a VBA code.

    average-in-vba-using-worksheet-function

    Let’s average values from the range A1:A10.

    1. First, enter the worksheet function property and then select the AVERAGE function from the list.
      2-worksheet-function-average
    2. Next, you need to enter starting parenthesis as you do while entering a function in the worksheet.
      3-enter-starting-paranthesis
    3. After that, we need to use the range object to refer to the range for which we want to calculate the average.
      4-ue-the-range-object
    4. In the end, type closing parenthesis and assign the function’s returning value to cell B1.
      5-type-close-pranthesis
    Application.WorksheetFunction.Average(Range("A1:A10"))

    Now when you run this code, it will calculate the average for the values that you have in the range A1:A10 and enter the value in cell B1.

    run-the-code-calculates-average

    Average Values from an Entire Column or a Row

    In that case, you just need to specify a row or column instead of the range that we have used in the earlier example.

    'for the entire column A
    Range("B1") = Application.WorksheetFunction.Average(Range("A:A"))
    
    'for entire row 1
    Range("B1") = Application.WorksheetFunction.Average(Range("1:1"))

    Use VBA to Average Values from the Selection

    Now let’s say you want to average value from the selected cells only in that you can use a code just like the following.

    Sub vba_average_selection()
    
    Dim sRange As Range
    Dim iAverage As Long
    
    On Error GoTo errorHandler
    
    Set sRange = Selection
    
    iAverage = WorksheetFunction.Average(Range(sRange.Address))
    MsgBox iAverage
    
    Exit Sub
    
    errorHandler:
    MsgBox "make sure to select a valid range of cells"
    
    End Sub

    In the above code, we have used the selection and then specified it to the variable “sRange” and then use that range variable’s address to get the average.

    VBA Average All Cells Above

    The following code takes all the cells from above and average values from them and enters the result in the selected cell.

    Sub vba_auto_Average()
    
    Dim iFirst As String
    Dim iLast As String
    Dim iRange As Range
    
    On Error GoTo errorHandler
    
    iFirst = Selection.End(xlUp).End(xlUp).Address
    iLast = Selection.End(xlUp).Address
    
    Set iRange = Range(iFirst & ":" & iLast)
    ActiveCell = WorksheetFunction.Average(iRange)
    
    Exit Sub
    
    errorHandler:
    MsgBox "make sure to select a valid range of cells"
    
    End Sub

    Average a Dynamic Range using VBA

    And in the same way, you can use a dynamic range while using VBA to average values.

    Sub vba_dynamic_range_average()
    
    Dim iFirst As String
    Dim iLast As String
    Dim iRange As Range
    
    On Error GoTo errorHandler
    
    iFirst = Selection.Offset(1, 1).Address
    iLast = Selection.Offset(5, 5).Address
    
    Set iRange = Range(iFirst & ":" & iLast)
    ActiveCell = WorksheetFunction.Average(iRange)
    
    Exit Sub
    
    errorHandler:
    MsgBox "make sure to select a valid range of cells"
    
    End Sub

    Average a Dynamic Column or a Row

    In the same way, if you want to use a dynamic column you can use the following code where it will take the column of the active cell and average for all the values that you have in it.

    Sub vba_dynamic_column()
    
    Dim iCol As Long
    
    On Error GoTo errorHandler
    
    iCol = ActiveCell.Column
    MsgBox WorksheetFunction.Average(Columns(iCol))
    
    Exit Sub
    
    errorHandler:
    MsgBox "make sure to select a valid range of cells"
    
    End Sub

    And for a row.

    Sub vba_dynamic_row()
    
    Dim iRow As Long
    
    On Error GoTo errorHandler
    
    iRow = ActiveCell.Row
    
    MsgBox WorksheetFunction.Average(Rows(iCol))
    
    Exit Sub
    
    errorHandler:
    MsgBox "make sure to select a valid range of cells"
    
    End Sub

    Sub Excel_AVERAGE_Function()

    Dim ws As Worksheet

    Set ws = Worksheets(«AVERAGE»)

    ws.Range(«C9») = Application.WorksheetFunction.Average(ws.Range(«C5:C8»))
    ws.Range(«D9») = Application.WorksheetFunction.Average(ws.Range(«D5:D8»))
    ws.Range(«E9») = Application.WorksheetFunction.Average(ws.Range(«E5:E8»))
    ws.Range(«F9») = Application.WorksheetFunction.Average(ws.Range(«F5:F8»))

    End Sub

    OBJECTS
    Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
    Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

    PREREQUISITES
    Worksheet Name: Have a worksheet named AVERAGE.

    ADJUSTABLE PARAMETERS
    Output Range: Select the output range by changing the cell references («C9»), («D9»), («E9») and («F9») in the VBA code to any cell in the worksheet, that doesn’t conflict with the formula.

    Содержание

    1. Метод WorksheetFunction.Average (Excel)
    2. Синтаксис
    3. Параметры
    4. Возвращаемое значение
    5. Замечания
    6. Поддержка и обратная связь
    7. Метод WorksheetFunction.AverageIfs (Excel)
    8. Синтаксис
    9. Параметры
    10. Возвращаемое значение
    11. Замечания
    12. Поддержка и обратная связь
    13. VBA Average – AVERAGE, AVERAGEA, AVERAGEIF
    14. AVERAGE WorksheetFunction
    15. Assign AVERAGE Result to a Variable
    16. AVERAGE with a Range Object
    17. AVERAGE Multiple Range Objects
    18. Using AVERAGEA
    19. Using AVERAGEIF
    20. VBA Coding Made Easy
    21. Disadvantages of WorksheetFunction
    22. Using the Formula Method
    23. Using the FormulaR1C1 Method
    24. VBA Code Examples Add-in
    25. Метод WorksheetFunction.AverageIf (Excel)
    26. Синтаксис
    27. Параметры
    28. Возвращаемое значение
    29. Замечания
    30. Поддержка и обратная связь

    Метод WorksheetFunction.Average (Excel)

    Возвращает среднее (среднее арифметическое) аргументов.

    Синтаксис

    Выражение Переменная, представляющая объект WorksheetFunction .

    Параметры

    Имя Обязательный или необязательный Тип данных Описание
    Arg1 — Arg30 Обязательный Variant От 1 до 30 числовых аргументов, для которых требуется среднее значение.

    Возвращаемое значение

    Double

    Замечания

    Аргументы могут быть числами или именами, массивами или ссылками, содержащими числа.

    Учитываются логические значения и текстовые представления чисел, которые вы вводите непосредственно в список аргументов.

    Если массив или ссылочный аргумент содержит текст, логические значения или пустые ячейки, эти значения игнорируются; однако включаются ячейки с нулевым значением.

    Аргументы, которые являются значениями ошибок или текстом, которые не могут быть преобразованы в числа, вызывают ошибки.

    Если вы хотите включить логические значения и текстовые представления чисел в ссылку в рамках вычисления, используйте функцию AVERAGEA.

    Метод Average измеряет центральную тенденцию, которая является расположением центра группы чисел в статистическом распределении. Три наиболее распространенных показателя центральной тенденции:

    • Среднее значение, которое является средним арифметическим и вычисляется путем сложения группы чисел, а затем деления на количество этих чисел. Например, среднее значение 2, 3, 3, 5, 7 и 10 равно 30, разделенное на 6, то есть 5.
    • Median— среднее число группы чисел; то есть половина чисел имеет значения, превышающие медиану, а половина чисел — значения, которые меньше медианы. Например, медиана 2, 3, 3, 5, 7 и 10 — 4.
    • Режим — наиболее часто встречающееся число в группе чисел. Например, режим 2, 3, 3, 5, 7 и 10 — 3.

    Для симметричного распределения группы чисел эти три меры центральной тенденции являются одинаковыми. При неравномерном распределении группы чисел они могут быть разными.

    При усреднении ячеек учитывайте разницу между пустыми и ячейками, содержащими нулевое значение, особенно если вы снимите флажок Нулевые значения на вкладке Вид (команда Параметры , меню Сервис ). Пустые ячейки не учитываются, но значения равны нулю.

    Поддержка и обратная связь

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

    Источник

    Метод WorksheetFunction.AverageIfs (Excel)

    Возвращает среднее (среднее арифметическое) для всех ячеек, соответствующих нескольким критериям.

    Синтаксис

    Выражение Переменная, представляющая объект WorksheetFunction .

    Параметры

    Имя Обязательный или необязательный Тип данных Описание
    Arg1 — Arg30 Обязательный Range Один или несколько диапазонов, в которых вычисляется связанный критерий.

    Возвращаемое значение

    Double

    Замечания

    Если ячейка в average_range является пустой ячейкой, AverageIfs игнорирует ее.

    Если ячейка в диапазоне условий пуста, AverageIfs обрабатывает ее как значение 0.

    Ячейки в диапазоне, содержащие Значение True , оцениваются как 1; ячейки в диапазоне, содержащие значение False , оцениваются как 0 (ноль).

    Каждая ячейка в average_range используется при вычислении среднего значения только в том случае, если для этой ячейки соответствуют все указанные условия.

    Если ячейки в average_range пустые или содержат текстовые значения, которые не могут быть преобразованы в числа, AverageIfs создает ошибку.

    Если нет ячеек, соответствующих всем критериям, AverageIfs создает значение ошибки.

    Используйте подстановочные знаки, вопросительный знак (?) и звездочку (*) в критериях. Вопросительный знак соответствует любому одному символу; звездочка соответствует любой последовательности символов. Если вы хотите найти фактический вопросительный знак или звездочку, введите тильду (

    Каждый criteria_range не обязательно должен иметь тот же размер и форму, что и average_range. Фактические усредненные ячейки определяются с помощью верхней левой ячейки в этой criteria_range в качестве начальной ячейки, а затем включает ячейки, соответствующие по размеру и форме диапазону. Например:

    Если average_range имеет значение И criteria_range Фактические вычисляемые ячейки:
    A1:A5 B1:B5 B1:B5
    A1:A5 B1:B3 B1:B5
    A1:B4 C1:D4 C1:D4
    A1:B4 C1:C2 C1:D4

    Метод AverageIfs измеряет центральную тенденцию, которая является расположением центра группы чисел в статистическом распределении. Три наиболее распространенных показателя центральной тенденции:

    • Среднее значение, которое является средним арифметическим и вычисляется путем сложения группы чисел, а затем деления на количество этих чисел. Например, среднее значение 2, 3, 3, 5, 7 и 10 равно 30, разделенное на 6, то есть 5.
    • Median— среднее число группы чисел; то есть половина чисел имеет значения, превышающие медиану, а половина чисел — значения, которые меньше медианы. Например, медиана 2, 3, 3, 5, 7 и 10 — 4.
    • Режим — наиболее часто встречающееся число в группе чисел. Например, режим 2, 3, 3, 5, 7 и 10 — 3.

    Для симметричного распределения группы чисел эти три меры центральной тенденции являются одинаковыми. При неравномерном распределении группы чисел они могут быть разными.

    Поддержка и обратная связь

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

    Источник

    VBA Average – AVERAGE, AVERAGEA, AVERAGEIF

    In this Article

    This tutorial will demonstrate how to use the Excel Average function in VBA.

    The Excel AVERAGE Function is used to calculate an average from a range cells in your Worksheet that have values in them. In VBA, It is accessed using the WorksheetFunction method.

    AVERAGE WorksheetFunction

    The WorksheetFunction object can be used to call most of the Excel functions that are available within the Insert Function dialog box in Excel. The AVERAGE function is one of them.

    You are able to have up to 30 arguments in the AVERAGE function. Each of the arguments must refer to a range of cells.

    This example below will produce the average of the sum of the cells B11 to N11

    The example below will produce an average of the sum of the cells in B11 to N11 and the sum of the cells in B12:N12. If you do not type the Application object, it will be assumed.

    Assign AVERAGE Result to a Variable

    You may want to use the result of your formula elsewhere in code rather than writing it directly back to an Excel Range. If this is the case, you can assign the result to a variable to use later in your code.

    AVERAGE with a Range Object

    You can assign a group of cells to the Range object, and then use that Range object with the WorksheetFunction object.

    AVERAGE Multiple Range Objects

    Similarly, you can calculate the average of the cells from multiple Range Objects.

    Using AVERAGEA

    The AVERAGEA Function differs from the AVERAGE function in that it create an average from all the cells in a range, even if one of the cells has text in it – it replaces the text with a zero and includes that in calculating the average. The AVERAGE function would ignore that cell and not factor it into the calculation.

    In the example below, the AVERAGE function returns a different value to the AVERAGEA function when the calculation is used on cells A10 to A11

    The answer for the AVERAGEA formula is lower than the AVERAGE formula as it replaces the text in A11 with a zero, and therefore averages over 13 values rather than the 12 values that the AVERAGE is calculating over.

    Using AVERAGEIF

    The AVERAGEIF Function allows you to average the sum of a range of cells that meet a certain criteria.

    The procedure above will only average the cells in range G5:G30 where the corresponding cell in column F has the word ‘Savings’ in it. The criteria you use has to be in quotation marks.

    VBA Coding Made Easy

    Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

    Disadvantages of WorksheetFunction

    When you use the WorksheetFunction to average the values in a range in your worksheet, a static value is returned, not a flexible formula. This means that when your figures in Excel change, the value that has been returned by the WorksheetFunction will not change.

    In the example above, the procedure TestAverage procedure has created the average of B11:M11 and put the answer in N11. As you can see in the formula bar, this result is a figure and not a formula.

    If any of the values change therefore in the Range(B11:M11 ), the results in N11 will NOT change.

    Instead of using the WorksheetFunction.Average, you can use VBA to apply the AVERAGE Function to a cell using the Formula or FormulaR1C1 methods.

    Using the Formula Method

    The formula method allows you to point specifically to a range of cells eg: B11:M11 as shown below.

    Using the FormulaR1C1 Method

    The FomulaR1C1 method is more flexible in that it does not restrict you to a set range of cells. The example below will give us the same answer as the one above.

    However, to make the formula more flexible, we could amend the code to look like this:

    Wherever you are in your worksheet, the formula will then average the values in the 12 cells directly to the left of it and place the answer into your ActiveCell. The Range inside the AVERAGE function has to be referred to using the Row (R) and Column (C) syntax.

    Both these methods enable you to use Dynamic Excel formulas within VBA.

    There will now be a formula in N11 instead of a value.

    VBA Code Examples Add-in

    Easily access all of the code examples found on our site.

    Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

    Источник

    Метод WorksheetFunction.AverageIf (Excel)

    Возвращает среднее (среднее арифметическое) всех ячеек в диапазоне, соответствующих заданным критериям.

    Синтаксис

    expression. AverageIf (Arg1, Arg2, Arg3)

    Выражение Переменная, представляющая объект WorksheetFunction .

    Параметры

    Имя Обязательный или необязательный Тип данных Описание
    Arg1 Обязательный Range Одна или несколько ячеек для среднего значения.
    Arg2 Обязательный Variant Критерии в виде числа, выражения, ссылки на ячейку или текста, определяющие усредненные ячейки. Например, критерии можно выразить как 32, «32», «>32», «яблоки» или B4.
    Arg3 Необязательный Variant Фактический набор ячеек для среднего значения. Если этот параметр опущен, используется диапазон.

    Возвращаемое значение

    Double

    Замечания

    Ячейки в диапазоне, содержащие значение True или False , игнорируются.

    Если ячейка в диапазоне или average_range является пустой ячейкой, AverageIf игнорирует ее.

    Если ячейка в критерии пуста, AverageIf обрабатывает ее как значение 0.

    Если никакие ячейки в диапазоне не соответствуют условиям, AverageIf создает значение ошибки.

    Используйте подстановочные знаки, вопросительный знак (?) и звездочку (*) в критериях. Вопросительный знак соответствует любому одному символу; звездочка соответствует любой последовательности символов. Если вы хотите найти фактический вопросительный знак или звездочку, введите тильду (

    Average_range не обязательно должны иметь тот же размер и форму, что и диапазон. Фактические усредненные ячейки определяются с помощью верхней, левой ячейки в average_range в качестве начальной ячейки, а затем включает ячейки, соответствующие по размеру и форме диапазону. Например:

    Если диапазон имеет значение И average_range Фактические вычисляемые ячейки:
    A1:A5 B1:B5 B1:B5
    A1:A5 B1:B3 B1:B5
    A1:B4 C1:D4 C1:D4
    A1:B4 C1:C2 C1:D4

    Метод AverageIf измеряет центральную тенденцию, которая является расположением центра группы чисел в статистическом распределении. Три наиболее распространенных показателя центральной тенденции:

    • Среднее значение, которое является средним арифметическим и вычисляется путем сложения группы чисел, а затем деления на количество этих чисел. Например, среднее значение 2, 3, 3, 5, 7 и 10 равно 30, разделенное на 6, то есть 5.
    • Median— среднее число группы чисел; то есть половина чисел имеет значения, превышающие медиану, а половина чисел — значения, которые меньше медианы. Например, медиана 2, 3, 3, 5, 7 и 10 — 4.
    • Режим — наиболее часто встречающееся число в группе чисел. Например, режим 2, 3, 3, 5, 7 и 10 — 3.

    Для симметричного распределения группы чисел эти три меры центральной тенденции являются одинаковыми. При неравномерном распределении группы чисел они могут быть разными.

    Поддержка и обратная связь

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

    Источник

    Содержание

    • СРЕДНИЙ рабочий лист
    • Присваивание СРЕДНЕГО результата переменной
    • СРЕДНИЙ с объектом диапазона
    • СРЕДНИЙ Объекты с несколькими диапазонами
    • Использование AVERAGEA
    • Использование AVERAGEIF
    • Недостатки WorksheetFunction

    Из этого туториала Вы узнаете, как использовать функцию Excel Average в VBA.

    Функция Excel AVERAGE используется для вычисления среднего значения из ячеек диапазона на вашем рабочем листе, в которых есть значения. В VBA доступ к нему осуществляется с помощью метода WorksheetFunction.

    СРЕДНИЙ рабочий лист

    Объект WorksheetFunction можно использовать для вызова большинства функций Excel, доступных в диалоговом окне «Вставить функцию» в Excel. Функция СРЕДНИЙ — одна из них.

    123 Sub TestFunctionДиапазон («D33») = Application.WorksheetFunction.Average («D1: D32»)Конец подписки

    У вас может быть до 30 аргументов в функции AVERAGE. Каждый из аргументов должен относиться к диапазону ячеек.

    В приведенном ниже примере будет получено среднее значение суммы ячеек от B11 до N11.

    123 Среднее значение теста ()Диапазон («O11») = Application.WorksheetFunction.Average (Диапазон («B11: N11»))Конец подписки

    В приведенном ниже примере будет получено среднее значение суммы ячеек от B11 до N11 и суммы ячеек в B12: N12. Если вы не введете объект Application, он будет принят.

    123 Среднее значение теста ()Range («O11») = WorksheetFunction.Average (Range («B11: N11»), Range («B12: N12»))Конец подписки

    Присваивание СРЕДНЕГО результата переменной

    Возможно, вы захотите использовать результат своей формулы в другом месте кода, а не записывать его непосредственно в диапазон Excel. В этом случае вы можете присвоить результат переменной, которая будет использоваться позже в вашем коде.

    1234567 Sub AssignAverage ()Уменьшить результат как целое число’Назначьте переменнуюresult = WorksheetFunction.Average (Диапазон («A10: N10»))’Показать результатMsgBox «Среднее значение для ячеек в этом диапазоне» & resultКонец подписки

    СРЕДНИЙ с объектом диапазона

    Вы можете назначить группу ячеек объекту Range, а затем использовать этот объект Range с Рабочий лист объект.

    123456789 Sub TestAverageRange ()Dim rng As Range’назначить диапазон ячеекУстановить rng = Диапазон («G2: G7»)’используйте диапазон в формулеДиапазон («G8») = WorksheetFunction.Average (rng)’отпустить объект диапазонаУстановить rng = ничегоКонец подписки

    СРЕДНИЙ Объекты с несколькими диапазонами

    Точно так же вы можете вычислить среднее значение ячеек из нескольких объектов диапазона.

    123456789101112 Sub TestAverageMultipleRanges ()Dim rngA As ДиапазонDim rngB as Range’назначить диапазон ячеекУстановите rngA = Range («D2: D10»)Установите rngB = Range («E2: E10»)’используйте диапазон в формулеДиапазон («E11») = WorksheetFunction.Average (rngA, rngB)’отпустить объект диапазонаУстановите rngA = NothingУстановить rngB = НичегоКонец подписки

    Использование AVERAGEA

    Функция СРЗНАЧ отличается от функции СРЗНАЧ тем, что она создает среднее значение из всех ячеек в диапазоне, даже если в одной из ячеек есть текст — она ​​заменяет текст нулем и включает его при вычислении среднего. Функция СРЗНАЧ игнорирует эту ячейку и не учитывает ее при вычислении.

    123 Sub TestAverageA ()Диапазон («B8) = Application.WorksheetFunction.AverageA (Диапазон (» A10: A11 «))Конец подписки

    В приведенном ниже примере функция СРЗНАЧ возвращает другое значение функции СРЗНАЧ, когда вычисление используется в ячейках с A10 по A11.

    Ответ для формулы AVERAGEA ниже, чем для формулы AVERAGE, поскольку она заменяет текст в A11 нулем и, следовательно, усредняет более 13 значений, а не 12 значений, по которым вычисляется AVERAGE.

    Использование AVERAGEIF

    Функция СРЗНАЧЕСЛИ позволяет усреднить сумму диапазона ячеек, отвечающих определенным критериям.

    123 Субсредний Если ()Диапазон («F31») = WorksheetFunction.AverageIf (Диапазон («F5: F30»), «Экономия», Диапазон («G5: G30»))Конец подписки

    Приведенная выше процедура будет усреднять только ячейки в диапазоне G5: G30, где в соответствующей ячейке в столбце F есть слово «Экономия». Используемые вами критерии должны быть заключены в кавычки.

    Недостатки WorksheetFunction

    Когда вы используете Рабочий лист для усреднения значений в диапазоне на вашем листе возвращается статическое значение, а не гибкая формула. Это означает, что при изменении ваших цифр в Excel значение, возвращаемое Рабочий лист не изменится.

    В приведенном выше примере процедура TestAverage создала среднее значение B11: M11 и поместила ответ в N11. Как вы можете видеть в строке формул, это число, а не формула.

    Если какое-либо из значений изменится в диапазоне (B11: M11), результаты в N11 будут НЕТ изменение.

    Вместо использования Рабочий листФункция.Среднее, вы можете использовать VBA для применения функции AVERAGE к ячейке с помощью Формула или Формула R1C1 методы.

    Использование метода формул

    Метод формулы позволяет указать конкретный диапазон ячеек, например: B11: M11, как показано ниже.

    123 Sub TestAverageFormula ()Диапазон («N11»). Формула = «= Среднее (B11: M11)»Конец подписки

    Использование метода FormulaR1C1

    Метод FomulaR1C1 более гибкий, поскольку он не ограничивает вас заданным диапазоном ячеек. Пример ниже даст нам тот же ответ, что и приведенный выше.

    123 Sub TestAverageFormula ()Диапазон («N11»). Формула = «= Среднее (RC [-12]: RC [-1])»Конец подписки

    Однако, чтобы сделать формулу более гибкой, мы могли бы изменить код, чтобы он выглядел так:

    123 Sub TestCountFormula ()ActiveCell.FormulaR1C1 = «= Счетчик (R [-11] C: R [-1] C)»Конец подписки

    Где бы вы ни находились на своем листе, формула затем усреднит значения в 12 ячейках слева от нее и поместит ответ в вашу ActiveCell. На диапазон внутри функции AVERAGE следует ссылаться с использованием синтаксиса Row (R) и Column (C).

    Оба эти метода позволяют использовать динамические формулы Excel в VBA.

    Теперь вместо значения в N11 будет формула.

    Вы поможете развитию сайта, поделившись страницей с друзьями

    Понравилась статья? Поделить с друзьями:
  • Vba excel сравнить столбец
  • Vba excel сравнить значения ячеек
  • Vba excel сумма прописью с копейками
  • Vba excel сумма по условию
  • Vba excel сумма значений массива