2017-06-19 113 views
1

似乎很簡單,但我沒有得到預期的結果。Excel VBA - 簡單平均計算

我嘗試,簡化用於說明:

Sub myMacro2() 

Dim intLastRow As Long 
Dim intLastCol As Long 
Dim numAve As Double 
Dim i As Integer 

intLastRow = ActiveSheet.UsedRange.Rows.Count 
intLastCol = ActiveSheet.UsedRange.Columns.Count 

For i = 1 To intLastRow Step 1 
    numAve = Application.WorksheetFunction.Average(Cells(i, 2), Cells(i, intLastCol)) 
    MsgBox "Row: " & i & " Ave: " & numAve 
Next i 

End Sub 

我對於此示例數據(5列,從左至右填充),爲NULL處理空單元。

A 111   
B 111   
C 111 222 333 444 
D 111 222  
E 111 222 333 
F 111 222  

msgBox返回「111」作爲每行的平均值。

我很確定我錯過了一些根本性的或顯而易見的事情,但它正在逃避我。

有什麼建議嗎?

+0

如果你想平均範圍,那麼它需要是'.Average(.Range(.Cells(I,2),.Cells(I,intLastCol)))'。這是假設你的範圍是正確的。還要注意合格的範圍和單元對象。 – Ambie

回答

3

您沒有正確定義範圍。

Application.WorksheetFunction.Average(Cells(i, 2), Cells(i, intLastCol)) 

應該是:

Application.WorksheetFunction.Average(Range(Cells(i, 2), Cells(i, intLastCol))) 
'         ^^^^^^^ 

不這樣做,你只是在平均細胞,而不是範圍加入兩個小區。

+1

A.S.H. - 謝謝,我在我的例子中用這種結構。啊! –

+1

@MarkPelletier樂於提供幫助。順便說一句,在我對數據的測試中,代碼在第3行獲得了「277.5」。想想如何改變你定義lastRow和lastCol的方式:「UsedRange」是不可靠的,並且從長遠來看會導致頭痛。 –