我是VBA的初学者,所以如果有人能给我一个明确的解释,那就太好了。 我写了以下内容,意图是每周平均(每行)没有空单元格。它在w_avg(i)步骤给我一个错误消息。
Sub weekly_avg()
Dim w_avg(19) As Long
Dim MyRange(19, 6) As Long
Dim i As Integer
Dim j As Integer
Cells(1, 11) = "Weekly Avg by VBA"
Cells(1, 11).Columns.AutoFit
For i = 0 To 19
For j = 0 To 6
MyRange(i, j) = Cells(i + 2, j + 3)
If Not Cells(i + 2, j + 3) = 0 Then
w_avg(i)=Worksheets("sheet1").WorksheetFunction.Average(Range(MyRange(i, 0),MyRange(i, j)))
Cells(i + 2, 11).Value = w_avg(i)
End If
Next j
Next i
End Sub
答案 0 :(得分:0)
Average()
函数是Excel.WorksheetFunction
对象的一种方法,而不是任何Worksheet
对象的方法:w_avg(i) = Excel.WorksheetFunction.Average(...)
。
答案 1 :(得分:0)
这里有几个问题
WorksheetFunction
是Application
对象的一种方法(实际上并不需要)Range(MyRange(i, 0),MyRange(i, j))
无法正常工作,因为MyRange(...)
值是数字。 (Cells(MyRange(i, 0),MyRange(i, j))
可能有用)For j
试试这个
Sub Demo()
Dim ws As Worksheet
Dim rng As Range
Dim i As Long
Dim OutputColumn As Long
Set ws = Worksheets("Sheet1")
ws.Cells(1, 11) = "Weekly Avg by VBA"
ws.Cells(1, 11).Columns.AutoFit
' Get a reference to the data range
Set rng = ws.Range("C2:I21")
' Specify output column relative to data range
OutputColumn = rng.Columns.Count + 2
With Application
For i = 1 To rng.Rows.Count
rng.Cells(i, OutputColumn).Value = _
.AverageIf(rng.Rows(i), "<>0")
Next
End With
End Sub