字符串数组上的 VBA“类型不匹配:需要数组或用户定义的类型”

The*_*per 5 excel vba

我有一个全局声明的字符串 DMA 的动态数组。

Dim DMAs() As String
Run Code Online (Sandbox Code Playgroud)

我重新调整数组并在 CreateArrayOf 函数中为其分配值,该函数是 String() 类型,该函数返回 String() 类型的数组

DMAs = CreateArrayOf(Sites, 2, "", False) 

Public Function CreateArrayOf( _
    ByRef arrayFrom() As String, _
    Optional ByVal numOfChars As Integer = 2, _
    Optional ByVal filterChar As String = "", _
    Optional ByVal filterCharIsInteger As Boolean = False _
) As String()

Dim i As Integer, _
    j As Integer, _
    strn As Variant, _
    switch As Boolean, _
    strArray() As String

'numOfChars 2 for DMA with no filterChar
'numOfChars 3 for W with filterChar "W"
'numOfChars 3 for A with filterChar "A"
'numofChars 2 for D with filterChar "D"

ReDim strArray(LBound(arrayFrom) To LBound(arrayFrom))  'required in order to
'not throw error on first iteration

For i = LBound(arrayFrom) To UBound(arrayFrom)  'iterate through each site
switch = False

For Each strn In strArray 'iterate through the array to find whether the
'current site already exists
     If strn = Mid(arrayFrom(i), 1, numOfChars) And Not strn = "" Then
        switch = True
    End If
Next strn

If switch = False Then 'if it doesn't exist add it to the array
    ReDim Preserve strArray(1 To UBound(strArray) + 1)
    strArray(UBound(strArray) - 1) = Mid(arrayFrom(i), 1, numOfChars)
End If
Next i

CreateArrayOf = strArray 'return the new array
End Function
Run Code Online (Sandbox Code Playgroud)

当我尝试将 DMA 数组传递给另一个函数 OutputAnArray 时

Private Sub OutputAnArray(ByRef arrayToOutput() As String)

Dim i As Variant
Dim x As Integer
x = 1
For Each i In arrayToOutput
    Cells(x, 6).Value = i
    x = x + 1
Next i

End Sub
Run Code Online (Sandbox Code Playgroud)

我得到“类型不匹配:预期的数组或用户定义的类型”。在整个过程中,我只处理字符串数组。

如果我获取 OutputAnArray 函数的内容并将其放入我从中调用它的父函数中,则一切正常。

任何帮助表示赞赏。

The*_*per 3

我将所有字符串定义更改为变体

Private Sub OutputAnArray(ByRef arrayToOutput() As Variant)
Run Code Online (Sandbox Code Playgroud)

罪魁祸首仍然存在,所以经过大量尝试使其编译后,我从参数中删除了 () arrayToOutput,它开始工作。

Private Sub OutputAnArray(ByRef arrayToOutput As Variant) 'fixed
Run Code Online (Sandbox Code Playgroud)

令人困惑的是,在下面的函数定义中,需要 () 来表示arrayFrom

Public Function CreateArrayOf(ByRef arrayFrom() As Variant, _ ...
Run Code Online (Sandbox Code Playgroud)

我真的不明白,如果有人有任何解释,我很想听听。