Excel VBA - 将列表作为函数参数传递

时间:2017-12-16 22:20:08

标签: excel vba

使用某些功能,您可以执行=SEARCH({"some","thing"},A1)

之类的操作

我怎样才能编写一个接受{"some","thing"}等参数的函数?

我根据我见过的其他一些答案/网站尝试了Function whatever(my_list as Variant)Function whatever(my_list() as Variant),但它不起作用,我不确定原因。

我认为如果我的函数类似于=WHATEVER("some","thing"),我会想要其他参数,例如=WHATEVER(A1,{"some","thing"},0,B1)

我希望在接受它作为参数后循环遍历列表。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用以下功能实现此目的:

Public Function Foo(values As Variant) As String
  Dim i As Long
  For i = LBound(values) To UBound(values)
    Foo = Foo & values(i)
  Next i
End Function

然后在Excel公式中使用它:

=Foo({"a","b","c"})

将返回abc的单元格值。

修改....

但该函数不会处理像=Foo({"a","b","c";"d","e","f"})这样的二维数组,也不会将范围传递给函数,例如=Foo(A1:B6)

这有点强大:

Public Function Foo(ByVal values As Variant) As String

  Dim temp As Variant
  temp = values

  Dim i As Long
  Dim j As Long
  Dim is2D As Boolean

  If IsArray(temp) Then
    On Error Resume Next
    is2D = IsNumeric(LBound(temp, 2))
    On Error GoTo 0

    If is2D Then
      For i = LBound(temp, 1) To UBound(temp, 1)
        For j = LBound(temp, 2) To UBound(temp, 2)
          Foo = Foo & temp(i, j)
        Next j
      Next i
    Else
      For i = LBound(temp) To UBound(temp)
        Foo = Foo & temp(i)
      Next i
    End If
  Else
    Foo = temp
  End If

End Function

答案 1 :(得分:0)

除了将参数声明为Variant之外,还可以使用IsArray来检查参数是否为数组,如果是For Each,则可以使用For代替Public Function MySearch(values, value) As Boolean If TypeOf values Is Excel.Range Then values = values ' convert Range to array or value If TypeOf value Is Excel.Range Then value = value ' not sure if this is needed .. If Not IsArray(values) Then MySearch = values = value : Exit Function Dim v ' As Variant by default For Each v In values If v = value Then MySearch = True : Exit Function Next i MySearch = False End Function 尺寸数量未知:

row_number()