Consulting

Results 1 to 4 of 4

Thread: Array Function?

  1. #1
    VBAX Expert
    Joined
    Feb 2005
    Posts
    929
    Location

    Array Function?

    Can a function be defined as an array and take on multiple values?

    For example,


    Function A(arg1, arg2, arg2) As Integer()
        Dim AA(3) As Integer
        AA(1) = arg1 + arg2
        AA(2) = arg1 * arg2
        AA(3) = arg1 / arg3
        A = AA
    End Function
    and, if so, how is the function referenced by the calling procedure?
    "It's not just the due date that's important, it's also the do date" [MWE]

    When your problem has been resolved, mark the thread SOLVED by clicking on the Thread Tools dropdown menu at the top of the thread.

  2. #2
    VBAX Expert xCav8r's Avatar
    Joined
    May 2005
    Location
    Minneapolis, MN, USA
    Posts
    912
    Location
    Function A(arg1, arg2, arg3) As Variant
    Dim AA(3) As Integer
    AA(1) = arg1 + arg2
    AA(2) = arg1 * arg2
    AA(3) = arg1 / arg3
    A = AA
    End Function
     
    Sub TestMyFunction()
    Dim varaMyArray As Variant
    varaMyArray = A(1, 2, 3)
    Debug.Print varaMyArray(1)
    Debug.Print varaMyArray(2)
    Debug.Print varaMyArray(3)
    End Sub

  3. #3
    VBAX Expert
    Joined
    Feb 2005
    Posts
    929
    Location
    This was too easy. I had tried essentially the same code as in your TestMyFunction but had dimensioned varaMyArray.

    Thanks
    "It's not just the due date that's important, it's also the do date" [MWE]

    When your problem has been resolved, mark the thread SOLVED by clicking on the Thread Tools dropdown menu at the top of the thread.

  4. #4
    VBAX Tutor
    Joined
    Mar 2005
    Posts
    268
    Location
    xCav8r has the answer for you. It's basically the only way of doing it (setting the function as a variant). You can't Dim or Redim the function with dimensions, but you can set the function to another array (as xCav8r shows, A= AA), use A = Array(x,y,z), or A = ActiveSheet.Cells(1,1).Resize(4,5) or whatever methods you know of for creating an array in a variant without explicitly dim'ing it as an array.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •