将数组传递给Excel VBA中的Sub ByRef

时间:2018-08-21 10:25:27

标签: arrays excel vba parameter-passing

我目前正在为我的工作开发项目。我有两个Sub,想用其中一个填充一个数组,并想在另一个Sub中使用它。很难解释,但这是到目前为止的代码:

Private Sub Find_CHNO(name As String, ByRef Myarray() As String)
Dim filter As String
Dim ws As Worksheet
Dim rng As Range
Dim i, j As Long

Set ws = Sheets("Stoffdatenbank")
Set rng = ws.Range("A1").CurrentRegion

filter = name

ReDim Myarray(4)

For i = 1 To rng.Rows.count
    If InStr(1, rng.Cells(i, 2), filter) > 0 Then
        For j = 1 To 4
            Myarray(j) = rng.Cells(i, j + 2)
        Next
    End If
Next
End Sub

Private Sub b_heizwert_calculate_Click()
Dim wC, wH, wN, wO, Hi As Double
Dim arr1(0 To 4), arr2(0 To 4), arr3(0 To 4) As String

If arrL3(0) = "" Then
    Call Find_CHNO(arrL1(0), arr1)
    Call Find_CHNO(arrL2(0), arr2)

    MsgBox arr1(0)
    'wC = arrL1(1) * arr1(1)
Else

End If

End Sub

每当我按下触发第二个Sub的按钮时,都会出现以下错误:

  

编译错误:不兼容的类型:数据字段或用户定义的类型应为

发生错误时,以下内容标记为蓝色:下一行中的“ arr1”:

Call Find_CHNO(arrL1(0), arr1)

1 个答案:

答案 0 :(得分:0)

当您将arr1(0到4),arr2(0到4),arr3(0到4)设为Dim时,只有最后一个是字符串数组。前两个是变量数组。

明确定义每个。

Dim arr1(0 To 4) As String, arr2(0 To 4) As String, arr3(0 To 4) As String

您还定义了arr1,arr2和arr3,但使用了arrL1,arrL2和arrL3,但我认为这只是一个错字,或者在其他地方公开声明了它们。