简体   繁体   中英

Passing Array to Sub ByRef in Excel VBA

I am currently working on a project for my job. I have two Subs and want to fill an array with one of those and want to use it in the other Sub. Its hard to explain but here is the code so far:

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

And

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

Whenever I press on the Button that triggers the second Sub I get the following error:

Compile Error: Incompatible Type: Data field or user-defined type expected

The following is marked blue when the error occurs: The "arr1" in the following line:

Call Find_CHNO(arrL1(0), arr1)

When you Dim arr1(0 To 4), arr2(0 To 4), arr3(0 To 4) As String only the last is a string array. The first two are variant arrays.

Define each definitively.

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

You are also defining arr1, arr2 and arr3 but using arrL1, arrL2 and arrL3 but I'll assume that is just a typo or they are publicly declared elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM