簡體   English   中英

通過VBA中的函數傳遞數組的字符串

[英]Passing String of arrays through a function in VBA

我正在創建幾個字符串數組,並嘗試對Excel工作表中的每個數組使用一個函數。 它應該遍歷每一行和每一行,以查看是否有任何字符串與當前活動單元格中的值匹配。 當我嘗試將字符串數組傳遞給函數並為函數參數獲取空值時,我似乎會出錯。 這是我的代碼

數組

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

功能

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

我叫它

 checkArray(anArray)

示例函數代碼似乎缺少一些必要的東西。

  1. 函數無法選擇要處理的單元格,但您可以將一個或多個單元格范圍作為要處理的參數傳遞給函數。
  2. 您已經使用VBA代碼描述了數組,但是沒有提到該函數如何確定數組的性質,而不僅僅是將其作為傳入參數輸入。 這與其余示例函數代碼的性質沖突,因為它看起來像將用作UDf工作表函數。

這是我希望作為工作表UDF函數使用的功能。

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

可選變量數組參數可以作為常量數組傳入,也可以由函數內存儲的默認值在函數內定義。

語法:= checkArray( <要檢查的單元格范圍><可選的字符串數組>
示例:= checkArray(A1:A10)
= checkArray(A1:A10,{“ abc”,“ def”,“ JKL”})

UDF函數與數組

也可以從Sub內部調用此函數,以將長整數值分配給已聲明的變量。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM