我正在尝试在VBA中执行统计功能,但我遇到了问题。我可以看到所有设置。平均功能正常,但其他功能都失败了。任何帮助都会很棒!
Private Sub CommandButton1_Click()
Dim Counter As Integer
Dim Count
Dim Total As Integer
Dim Average As Integer
Dim Std_Dev As Integer
Dim Max As Integer
Dim Min As Integer
Dim Median As Integer
With ListBox1
For Counter = 0 To .ListCount - 1
If .Selected(Counter) Then
Count = Count + 1
Total = Total + .List(Counter)
End If
Next Counter
End With
Average = (Total / Count)
'Std_Dev = Application.WorksheetFunction.StDev_S()
Max = Application.WorksheetFunction.Max(ListBox1.ListCount)
'Min = Application.WorksheetFunction.Min()
'Median = Application.WorksheetFunction.Median()
Unload Me
MsgBox "Test. " & Std_Dev
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Private Sub UserForm_Click()
End Sub
Private Sub UserForm_Initialize()
For Each cell In Range("Scores")
ListBox1.AddItem cell.Value
Next
End Sub
答案 0 :(得分:0)
您必须仔细阅读MSDN帮助主题(例如https://msdn.microsoft.com/en-us/library/office/ff838412.aspx)并且您会发现:
这些函数输出Double
数据类型值
他们需要填补论据......
所以以下可能是一个可能的代码
Option Explicit
Private Sub CommandButton1_Click()
Dim Counter As Integer, selectedCounter As Integer
Dim Total As Double, Average As Double, Std_Dev As Double, Max As Double, Min As Double, Median As Double '<== use "Double" data type, since this is the return value of those functions
Dim numArr() As Integer '<== use an array to store selected items
With Me.ListBox1
ReDim numArr(1 To .ListCount) As Integer '<== dim array to its maximum possible size
For Counter = 0 To .ListCount - 1
If .Selected(Counter) Then
selectedCounter = selectedCounter + 1
numArr(selectedCounter) = .List(Counter)
End If
Next Counter
End With
ReDim Preserve numArr(1 To selectedCounter) As Integer '<== redim array to its actual size
Total = Application.WorksheetFunction.Sum(numArr)
Average = Application.WorksheetFunction.Average(numArr)
Std_Dev = Application.WorksheetFunction.StDev_S(numArr)
Max = Application.WorksheetFunction.Max(numArr)
Min = Application.WorksheetFunction.Min(numArr)
Median = Application.WorksheetFunction.Median(numArr)
Unload Me
MsgBox "Test Results:" & vbCrLf _
& vbCrLf & "Total: " & Total _
& vbCrLf & "Average: " & Average _
& vbCrLf & "Std_Dev: " & Std_Dev _
& vbCrLf & "Max: " & Max _
& vbCrLf & "Min: " & Min _
& vbCrLf & "Median: " & Median
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Private Sub UserForm_Initialize()
Dim cell As Range
'Me.ListBox1.List = Application.Transpose(Range("Scores")) '<== consider this if "Scores" is a one-column range
For Each cell In Range("Scores")
Me.ListBox1.AddItem cell.Value
Next
End Sub