将一系列单元格从excel传递到vba中的函数

时间:2011-12-28 23:46:19

标签: excel vba

我正在尝试创建一个函数,以便= processCells(A1:A10)将获取单元格范围并允许我为每个项目添加10并在单元格A11:A20中显示新数字。我想在工作表中使用该功能,以便用户可以手动选择单元格A1:A10,因此可以选择B1:B10等...而不是A1:A10

我的问题是将工作表的单元格范围传递给函数,然后处理它们。

1 个答案:

答案 0 :(得分:2)

这是一个让你入门的样本UDF

Function processCells(rng As Variant, Optional AddValue = 10) As Variant
    Dim v As Variant
    Dim i As Long, j As Long
    Select Case TypeName(Application.Caller)
        Case "Range"
            ' Called from a Formula
            v = rng
            If IsArray(v) Then
                ' Called from an Array Formula
                For j = 1 To UBound(v, 1)
                For i = 1 To UBound(v, 2)
                    If IsNumeric(v(j, i)) Then
                        v(j, i) = v(j, i) + AddValue
                    End If
                Next i, j
            Else
                ' Called from a single Cell
                If IsNumeric(v) Then
                    v = v + AddValue
                End If
            End If
            processCells = v
        Case Else
            processCells = vbEmpty
    End Select
End Function

要在描述时使用它,请在单元格单元格=processCells(A1:A10)

中将其作为数组公式A11:A20输入