2016-04-29 78 views
0

我想在VBA中執行統計函數,但我已經跑到了牆上。你已經看到了一切設置。平均功能正常工作,但其他人失敗。任何幫助將是驚人的!在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

,你必須仔細閱讀MSDN幫助主題(例如https://msdn.microsoft.com/en-us/library/office/ff838412.aspx),你會發現:

  • 這些功能輸出Double數據類型值

  • 他們所需要的參數被填充...

so so以下可能是一個可能的代碼

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 
+0

我不能非常感謝你!我爲此工作了6個多小時,但無法弄清楚。你從字面上來說是一種拯救生命! – Anonymity21

+0

不客氣 – user3598756