VBA:连续满足三个标准并输出这些行的其他单元格的平均值

时间:2017-10-26 12:10:57

标签: excel vba

我正在尝试在符合三个条件的Excel文件中搜索行。它们位于K,L和AJ列中。如果满足那些Kriterias,我想看看价格(第AM栏)。如果有多个行符合标准,我会找到平均价格,您可以在输出单元格中看到它。

我不知道我做错了什么。我总是从最后一个if循环中获取MsgBox。

非常感谢任何帮助

非常感谢!

Option Explicit

Sub FindAndAverage()

    Dim findenPN As String
    Dim findenVend As String
    Dim findenWS As String
    Dim Preis As Double
    Dim Added As Double
    Dim Anzahl As Long
    Dim iRow As Long
    Dim RowMax As Long
    Dim Avrg As Double

    'fill Variables 
    findenPN = Worksheets("Sheet2").Range("C3").Value
    findenPN = Worksheets("Sheet2").Range("C4").Value
    findenPN = Worksheets("Sheet2").Range("C5").Value
    Preis = 0
    Added = 0
    Anzahl = 0
    iRow = 2
    Avrg = 0

    With ThisWorkbook.Worksheets("Sheet1").Activate

        RowMax = ActiveSheet.UsedRange.Rows.Count

        For iRow = 2 To RowMax

            If Cells(iRow, 12).Value = findenPN And Cells(iRow, 11).Value = findenVend And Cells(iRow, 36).Value = findenWS Then

                'Look fpor price in column AM 
                Preis = Cells(iRow, 39).Value

                'Add price to other results
                Added = Added + Preis

                'go to next row
                iRow = iRow + 1

                'Add one for Average
                Anzahl = Anzahl + 1

            Else
                iRow = iRow + 1

            End If

        Next iRow

    End With

    If Anzahl > 0 Then

        'Output in Sheet2
        With ThisWorkbook.Worksheets("Sheet2").Activate

        Avrg = Added / Anzahl

        Range("C9").Value = Avrg

        End With

    Else

        MsgBox ("Kein Ergebniss!")

    End If

End Sub

2 个答案:

答案 0 :(得分:1)

你真的不需要VBA。工作表公式就足够了:

=AVERAGEIFS(Sheet1!M:M,Sheet1!K:K,Sheet1!C3,Sheet1!L:L,Sheet1!C4,Sheet1!AJ:AJ,Sheet1!C5)

答案 1 :(得分:0)

您正在声明3个变量,但是对于其余代码,您将留下2个空,验证将永远不会遇到这种情况。

Dim findenPN As String
Dim findenVend As String
Dim findenWS As String

'fill Variables 
findenPN = Worksheets("Sheet2").Range("C3").Value
findenPN = Worksheets("Sheet2").Range("C4").Value
findenPN = Worksheets("Sheet2").Range("C5").Value

您缺少声明findenVendfindenWS值。