Excel VBA for语句

来源:百度知道 编辑:UC知道 时间:2024/06/24 19:01:49
有一个 macro,但是却用不了自定义函数, 请问这样写有什么问题吗?
谢谢!

Function sim(time As Integer)
Dim i, j As Integer
Dim rng As Range
Set rng = Range("e25:e30")
For i = 0 To time Step 1
j = Application.WorksheetFunction.Average(rng)
Cells(25 + i, 7) = j
Next i
End Function

1、你的程序实现的目的是:先计算出E25:E30之间数据的平均值,然后向G25-----G(25+time)单元格写time+1次平均值;
2、你的过程中少一判断:即如果E25:E30单元格全部为空值时,程序就会判为有0个数据求平均值,就会造成“0/0”无意义的错误。因此,该程序应改为:
Function sim(time As Integer)
Dim i, j As Integer
Dim rng As Range
Set rng = Range("e25:e30")
If Application.WorksheetFunction.CountBlank(rng) <> 6 Then '进行是否全为空值的判断
For i = 0 To time Step 1
j = Application.WorksheetFunction.Average(rng)
Cells(25 + i, 7) = j
Next i
End If
End Function