通过VBA中的函数传递数组的字符串

Passing String of arrays through a function in VBA

我正在创建几个字符串数组,并尝试对Excel工作表中的每个数组使用一个函数。它应该遍历每一行和每一行,以查看是否有任何字符串与当前活动单元格中的值匹配。当我尝试将字符串数组传递给函数并为函数参数获取空值时,我似乎会出错。这是我的代码

数组

1
anArray = Array("string1","string2","string3")

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Function checkArray(a as Variant) as integer

   Range("A1")
   Dim count As Integer
   count = a.Length - 1

   Do While ActiveCell.Value <>""        

    Do While count <> -1

        If ActiveCell.Value = a(count) Then  
            checkArray = checkArray + 1
        End If
        count = count -1
    Next i

       ActiveCell.Offset(1, 0).Select    
    Loop
  End Function

我叫它

1
 checkArray(anArray)


示例函数代码中似乎缺少一些必要的东西。

  • 函数无法选择要处理的单元格,但是您可以将一个或多个单元格范围作为要处理的参数传递给函数。
  • 您已经使用VBA代码描述了数组,但是没有提到该函数如何确定数组的性质,而不仅仅是将其作为传入参数输入。这与其余示例函数代码的性质冲突,因为它看起来像用作UDf工作表函数。
  • 这是我希望作为工作表UDF函数使用的功能。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Function checkArray(rng As Range, Optional a As Variant) As Long
        Dim v As Long, vSTRs As Variant

        If IsMissing(a) Then
            vSTRs = Array("string1","string2","string3")
        Else
            vSTRs = a
        End If

        For v = LBound(vSTRs) To UBound(vSTRs)
            checkArray = checkArray + Application.CountIf(rng, vSTRs(v))
        Next v

    End Function

    可选的变量数组参数可以作为常量数组传入,也可以由函数内存储的默认值在函数内定义。

    Syntax: =checkArray(,)
    Examples: =checkArray(A1:A10)
    =checkArray(A1:A10, {"abc","def","JKL"})

    UDF

    1
    2
    3
    4
    5
    Sub test()
        Dim num As Long
        num = checkArray(ActiveSheet.Range("A1:A10"), Array("string1","string2","string3"))
        Debug.Print num
    End Sub