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
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
2条答案
按热度按时间dxxyhpgq1#
这可能有助于澄清,它向ListBox添加了一个Click事件方法......因此,单击ListBox中的一个条目,消息将告诉您他们所知道的有关该条目的信息
或者,如果您想知道总体平均值,只需将第2列的所有条目相加,然后除以条目数
pokxtpni2#
从列表框列中获取平均值
Application.Average
从数组中检索平均值并将其写入标签。