Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing an integer and an array of integers to a VBA function

Tags:

excel

vba

I'm trying to pass an integer and an array of integers to a function to check whether the integer is a member of the array.The arrowed line gives a compile error msg as: "expect:= ".

Public Sub mainSub()
B = Array(4, 5, 6, 7, 8, 9)
ckArr(4,B) '<-------
End Sub

Public function ckArr(N As Integer, A() As Integer)
For i = 0 To UBound(A)
If N = A(i) And i <= UBound(A) Then
    Debug.Print N; " Is in the List"
    Exit For 'Do
ElseIf i < UBound(A) Then GoTo NXT
Else:
    Debug.Print N; " Is NOT in the List"
    Exit For 'Do
End If
NXT:
'i = i + 1
Next 'Loop
End function
like image 764
musa yusuf Avatar asked Dec 26 '22 02:12

musa yusuf


2 Answers

To call a function either use:

a = func(b,c)

or if you are not interessted in the result do:

call func(b, c)

or

func b, c

Doing

func(b,c)

is not valid.


So in your particular case, it would be:

Public Sub mainSub()  
  B = Array(4, 5, 6, 7, 8, 9)
  Call ckArr(4,B) '<-------
End Sub

or

Public Sub mainSub()  
  B = Array(4, 5, 6, 7, 8, 9)
  ckArr 4, B '<-------
End Sub
like image 162
alk Avatar answered Mar 06 '23 07:03

alk


Try below code:

Public Sub mainSub()
    Dim IsMember As Boolean
    b = Array(4, 5, 6, 7, 8, 9)

    Dim checkVariable As Integer
    checkVariable = 4
    IsMember = ckArr(checkVariable, b)

    If IsMember Then
    MsgBox checkVariable & " is a member of member of array"
    Else
    MsgBox checkVariable & " is not a member of member of array"
    End If
End Sub

Public Function ckArr(N As Integer, A As Variant) As Boolean
    For i = LBound(A) To UBound(A)

        If N = A(i) Then
            ckArr = True
            Exit Function
        End If
    Next

End Function

enter image description here

B = Array(4, 5, 6, 7, 8, 9) so B is variant here.

So i have made parameter of below procedure as variant.

From Public function ckArr(N As Integer, A() As Integer)

To Public Function ckArr(N As Integer, A As Variant) As Boolean

like image 33
Santosh Avatar answered Mar 06 '23 09:03

Santosh