2014-09-21 366 views
0

我試圖編寫一個簡短的宏,其中包含一行代表平均值範圍的單元格。在每個工作表中,我想要在單元格範圍內運行宏是不同的長度。在VBA excel中取平均值不同的長度範圍

運行宏後,小區E1包含"=AVERAGE(Rng)"

Dim homeSheet As Worksheet 
    Set homeSheet = ActiveSheet 
    Dim lastRow As Long 
    Dim Rng As Range 
    lastRow = Range("A" & Rows.Count).End(xlUp).Row 

    Set Rng = Range("B2:B" & lastRow) 
    Range("E1").Formula = "=Average(Rng)" 
    Range("E2").Formula = "=STDEV(Rng)" 
    Range("E3").Select 
    ActiveWindow.SmallScroll Down:=-2 
End Sub 

我也試過

Range("E1").Formula = "=Average(Range("B2:B" & lastRow))" 

,但不嘗試使用Set Rng = Range("B2:B" & lastRow)

回答

1

你需要在公式中使用Rng.Address。嘗試改變你的代碼如下:

Sub Avg() 
    Dim homeSheet As Worksheet 
    Set homeSheet = ActiveSheet 
    Dim lastRow As Long 
    Dim Rng As Range 
    lastRow = Range("A" & Rows.Count).End(xlUp).Row 

    Set Rng = Range("B2:B" & lastRow) 
    Range("E1").Formula = "=Average(" & Rng.Address & ")" 
    Range("E2").Formula = "=STDEV(" & Rng.Address & ")" 
    Range("E3").Select 
End Sub 

如果你使用你已經嘗試了第二種方法,你需要到該行的代碼更改爲:

Range("E1").Formula = "=Average(" & Range("B2:B" & lastRow).Address & ")" 
+0

工作很漂亮,謝謝! – Amos 2014-09-21 11:13:33