So I was wondering, how can I return multiple values from a function, sub or type in VBA? I've got this main sub which is supposed to collect data from several functions, but a function can only return one value it seems. So how can I return multiple ones to a sub?
Summary. JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object.
We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.
Strings or whatever, you can only return one Thing. Thing may be a single string, or it may be an object that contains multiple properties that are themselves strings. But you cannot return multiple Things.
You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.
You might want want to rethink the structure of you application, if you really, really want one method to return multiple values.
Either break things apart, so distinct methods return distinct values, or figure out a logical grouping and build an object to hold that data that can in turn be returned.
' this is the VB6/VBA equivalent of a struct ' data, no methods Private Type settings root As String path As String name_first As String name_last As String overwrite_prompt As Boolean End Type Public Sub Main() Dim mySettings As settings mySettings = getSettings() End Sub ' if you want this to be public, you're better off with a class instead of a User-Defined-Type (UDT) Private Function getSettings() As settings Dim sets As settings With sets ' retrieve values here .root = "foo" .path = "bar" .name_first = "Don" .name_last = "Knuth" .overwrite_prompt = False End With ' return a single struct, vb6/vba-style getSettings = sets End Function
You could try returning a VBA Collection.
As long as you dealing with pair values, like "Version=1.31", you could store the identifier as a key ("Version") and the actual value (1.31) as the item itself.
Dim c As New Collection Dim item as Variant Dim key as String key = "Version" item = 1.31 c.Add item, key 'Then return c
Accessing the values after that it's a breeze:
c.Item("Version") 'Returns 1.31 or c("Version") '.Item is the default member
Does it make sense?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With