Excel VBA使用范围作为input
我正在学习Excel VBA,并试图创build一个简单的函数。
这个想法是,我将使用一个单元格作为input,该函数会告诉你在该单元格周围放置12个值的标准偏差。
所以如果我inputgetstd(A1),它会得到A1,A3,A5,A7,C1,C3,C5,C7和E1,E3,E5和E7的标准偏差。
如果我inputgetstd(X23),它将获得12个其他值的标准位于X23周围相同的偏移量。
我现在最大的问题是搞清楚如何使用单元格作为input。
例如,当试验抵消时:
Function getstd(rng as Range) Range(rng).Offset(1,1) = "hello world" End Function
它总是给我一个#值错误。
我觉得,如果我可以做到这一点,那么创build我的function应该很容易。
谢谢!
迈克尔
您可以将单元格( Union
)组合成一个多区域范围,并使用内置的stdev
函数:
Function getstd(ByVal target As Range) Dim r As Range For i = 0 To 6 Step 2 For j = 0 To 4 Step 2 If r Is Nothing Then Set r = target.Offset(i, j) Else Set r = Union(r, target.Offset(i, j)) Next Next getstd = Application.StDev(r) End Function
另一种方法来做到这一点:
Public Function STD_DEV() As Variant Dim rDataSet As Range Dim rCell As Range Dim aValues(1 To 8) As Double Dim x As Long Application.Volatile With Application.ThisCell 'Check we're not trying to reference off the sheet. If .Row > 1 And .Column > 1 And _ .Row < Rows.Count And .Column < Columns.Count Then 'Get a reference to all cells around target cell. 'This includes the target cell in its reference. Set rDataSet = .Offset(-1, -1).Resize(3, 3) 'Step through each cell in the range and add 'value to an array. x = 1 For Each rCell In rDataSet If rCell.Address <> .Address Then aValues(x) = rCell.Value x = x + 1 End If Next rCell 'Calculate the Standard Deviation. STD_DEV = WorksheetFunction.StDev(aValues) Else STD_DEV = CVErr(xlErrRef) End If End With End Function
请注意WITH
关键字 – WITH
和END WITH
之间以.
开头的任何内容.
指的是Application.ThisCell
。 所以.Row
和Application.ThisCell.Row
是一样的
编辑:已经更新的函数返回一个#REF!
错误,如果它试图引用closures表。