【问题标题】:Excel VBA use range as inputExcel VBA 使用范围作为输入
【发布时间】:2015-12-29 19:43:44
【问题描述】:

我正在学习 Excel VBA,正在尝试创建一个简单的函数。

我的想法是我将使用一个单元格作为输入,该函数会告诉您该单元格周围 12 个值的标准偏差。

因此,如果我输入 getstd(A1),它将得到 A1、A3、A5、A7、C1、C3、C5、C7 和 E1、E3、E5 和 E7 的标准差。

如果我输入 getstd(X23),它将获得 12 个其他值的标准值,这些值位于 X23 周围的相同偏移处。

我现在最大的问题是弄清楚如何使用单元格作为输入。

例如,在尝试偏移时:

Function getstd(rng as Range)

     Range(rng).Offset(1,1) = "hello world"

End Function

它总是给我一个 #Value 错误。

我觉得如果我可以让它工作,那么创建我的函数应该很容易。

谢谢!

迈克尔

【问题讨论】:

  • Range(rng).Offset(1,1 只做rng.Offset(1,1)
  • 虽然@findwindow 说的是正确的语法,但UDF 不会更改与调用者不同的单元格的值(没有一些时髦的回避)。要了解偏移量,请将行更改为getstd = rng.offset(1,1).value,它将返回指定范围的下一行和上一列的值。
  • 永远听斯科特的声音。
  • @findwindow 刚试过。仍然给我一个#Value 错误。在单元格 W23 中,我键入 =getstd(X12),我希望它会在单元格 Y13 中输入“hello world”,但它没有...
  • @ScottCraner 谢谢,是的,这很有道理。

标签: excel vba input


【解决方案1】:

您可以将单元格(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

【讨论】:

    【解决方案2】:

    另一种方法:

    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 关键字 - WITHEND WITH 之间以 . 开头的任何内容都指的是 Application.ThisCell。所以.RowApplication.ThisCell.Row是一样的

    编辑:已更新函数以在尝试从工作表外引用时返回 #REF! 错误。

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多