查找平均输入框VBA

时间:2018-05-26 16:37:45

标签: vba excel-vba excel

我在L栏上有很多成绩。我想要一个输入框,然后我想为A栏中的学生写一个学生ID。我想知道是否有办法可以计算出来只有使用student_id,学生与student_id的所有成绩的平均值? 像这样的东西,但这不起作用:

 Dim StudentID As String
 Dim LastRow As Long
 Dim cell As Range
 Dim sum As Long
 Dim RowCount As Long



 StudentID = InputBox("Please enter a Student_ID:")
 LastRow = Cells(Rows.count, "A").End(xlUp).Row

 sum = 0
 RowCount = 0

 For Each cell In Range("A:A2" & LastRow)
 If cell.Value = StudentID Then 
 sum = sum + Cells(cell.Row, 12)
 RowCount = RowCount + 1
 Next cell

 avg = sum / RowCount
 MsgBox avg

2 个答案:

答案 0 :(得分:1)

您的代码中只有一些语法错误。

Sub GetStudentAverage()
    Dim StudentID As String
    Dim LastRow As Long
    Dim cell As Range
    Dim sum As Long
    Dim RowCount As Long

    StudentID = InputBox("Please enter a Student_ID:")
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row

    sum = 0
    RowCount = 0

    For Each cell In Range("A2:A" & LastRow)
        If cell.Value = StudentID and IsNumeric(Cells(cell.Row, 12)) Then
            sum = sum + Cells(cell.Row, 12)
            RowCount = RowCount + 1
        End If
    Next cell

    If RowCount > 0 Then
        avg = sum / RowCount
    Else
        avg = "No Matches Found!"
    End If
    MsgBox avg
End Sub

你错过了End If并且范围不合适。另外,为了避免除以0,只需检查rowcount是否为> 0.

答案 1 :(得分:0)

这可以通过公式

轻松实现
=AVERAGEIFS(L:L,A:A,"StudentID")

或更简单地在VBA中

Sub Demo()
    Dim StudentID As Variant
    Dim avg As Variant

    StudentID = Application.InputBox("Please enter a Student ID:")
    If Not StudentID = False Then
        avg = Application.AverageIfs(Columns(12), Columns(1), StudentID)
        If Not IsError(avg) Then MsgBox avg
    End If
End Sub