Pass Array as parameter in VBA (Excel)

Asked

Viewed 1,337 times

2

How do I pass an Array as a parameter to a function in VBA? Detail if I define a type of variable like String, Integer, etc... works, however a type defined by me, does not work! For example:

Type pessoa
    nome As String
    idade As Integer
End Type

Public Sub SomaIdade(arrPessoa As Variant)
    Dim soma As Integer
    For i = 0 To UBound(arrPessoa)
        soma = som + arrPessoa(i)
    Next i
    Debug.Print (soma)
End Sub

Sub main()
    Dim p(2) As pessoa
    p(0).idade = 10
    p(1).idade = 20
    p(2).idade = 30

    SomaIdade (p)
End Sub
  • I did some research and it seems that there is no way.

1 answer

1


You had a syntax problem, because you don’t want to pass an array, but rather the user-defined type pessoa, see the codes below:

Function

Public Type pessoa
    Nome As String
    Idade As Long
End Type

Public Function SomaIdade(ByRef arrPessoa() As pessoa)
    Dim soma As Long
    For i = 0 To UBound(arrPessoa)
        soma = soma + arrPessoa(i).Idade
    Next i
    SomaIdade = soma
End Function

Sub main()
    Dim p() As pessoa
    Dim soma_idade As Long
    ReDim p(0 To 2)
    p(0).Idade = 10
    p(1).Idade = 20
    p(2).Idade = 30


    soma_idade = SomaIdade(p())
    Debug.Print soma_idade
End Sub

Sub

Public Type pessoa
    Nome As String
    Idade As Long
End Type

Public Sub SomaIdade(ByRef arrPessoa() As pessoa)
    Dim soma As Long
    For i = 0 To UBound(arrPessoa)
        soma = soma + arrPessoa(i).Idade
    Next i
    Debug.Print (soma)
End Sub

Sub main()
    Dim p() As pessoa
    ReDim p(0 To 2)
    p(0).Idade = 10
    p(1).Idade = 20
    p(2).Idade = 30

    SomaIdade p()
End Sub
  • It worked, thank you very much! I spent 4hs trying to solve this problem, now that you solved, it seems the most obvious thing in the world rsrs, is part!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.