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) |
示例函数代码中似乎缺少一些必要的东西。
这是我希望作为工作表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"})
也可以从Sub内部调用此函数,以将长整数值分配给已声明的变量。
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 |