excel VBA:UserForm如何使用数组计算第二列中列表框的平均值

mzillmmw  于 2022-11-26  发布在  其他
关注(0)|答案(2)|浏览(181)

我很难找到从列表框中取平均值,然后在用户窗体上显示该平均值的方法。我知道您应该使用数组,但我现在很困惑如何在列表框中排列第二列。下面是一个示例,文本框中的数字需要取平均值,然后显示在我的圆圈中

dxxyhpgq

dxxyhpgq1#

这可能有助于澄清,它向ListBox添加了一个Click事件方法......因此,单击ListBox中的一个条目,消息将告诉您他们所知道的有关该条目的信息

Private Sub ListBox1_Click()
   MsgBox Me.ListBox1.Value
   MsgBox Me.ListBox1.ListIndex
   MsgBox Me.ListBox1.List(Me.ListBox1.ListIndex, 0)  ' The Value of Column 1
   MsgBox Me.ListBox1.List(Me.ListBox1.ListIndex, 1)  ' The Value of Column 2
End Sub

或者,如果您想知道总体平均值,只需将第2列的所有条目相加,然后除以条目数

Private Sub ListBox1_Click()
   Dim i As Long
   Dim iMax As Long
   Dim SubTot As Double
   
   SubTot = 0
   iMax = UBound(Me.ListBox1.List)
   For i = 0 To iMax
      SubTot = SubTot + Me.ListBox1.List(i, 1)
   Next i
   MsgBox "The Average of ALL people is " & Round((SubTot / (iMax + 1)), 2)
End Sub
pokxtpni

pokxtpni2#

从列表框列中获取平均值

  • 这个例子使用了一个Active-X列表框和工作表上的标签。当然,您可以设法将它应用到您的用户窗体案例中。
  • 它使用循环将列表框第2列中的数字写入数组,使用Application.Average从数组中检索平均值并将其写入标签。
Sub ListBoxAverage()
    
    Dim Players() As Variant: Players = VBA.Array("Tim", "Jon", "Sue")
    Dim Numbers() As Variant: Numbers = VBA.Array(1, 2, 4)
    
    Dim rUpper As Long: rUpper = UBound(Players)
    
    Dim Arr() As Double ' Array to Hold the Numbers
    Dim r As Long ' List Box Row Counter
    Dim n As Long ' Array Element Counter
    
    With Sheet1.ListBox1
        ' Populate.
        .Clear
        .ColumnCount = 2
        For r = 0 To rUpper
            .AddItem
            .List(r, 0) = Players(r) ' 1st column
            .List(r, 1) = Numbers(r) ' 2nd column
        Next r
        ' Write the values from the 2nd column to a Double array.
        ReDim Arr(0 To rUpper)
        Dim rValue As Variant
        For r = 0 To rUpper ' .ListCount - 1
            rValue = .List(r, 1) ' 2nd column
            If IsNumeric(rValue) Then ' it's a number
                Arr(n) = CDbl(rValue)
                n = n + 1
            'Else ' it's not a number; do nothing
            End If
        Next r
    End With
    
    With Sheet1.Label1
        ' Write the average to the label.
        If n = 0 Then
            .Caption = "No average."
        Else
            If n < r Then
                ReDim Preserve Arr(0 To n - 1)
            End If
            .Caption = Format(Application.Average(Arr), "0.0")
        End If
    End With
    
End Sub

相关问题