API reference · Arrays

Exchange

Swap two Variant values in the caller through ByRef arguments.

FunctionArrays→VariantSource L48

Signature#

VBA
Function Exchange(ByRef val_a, ByRef val_b) As Variant

Parameters#

ParameterVBA typeDefaultDescription
val_aVariantByRefRequiredFirst value. The parameter has no explicit As clause, so its type is Variant. It is replaced with the original val_b.
val_bVariantByRefRequiredSecond Variant value, replaced with the original val_a. Pass writable variables of compatible type.

Returns#

Variant containing Empty. This function never assigns a value to its function name; the useful result is the change to both ByRef arguments.

Example#

SEE THE TRANSFORMATIONSwap the two variables
Before
BeforeValues / state

No array dimensions

ItemValue
debit125.5
credit80
After
AfterValues / state

No array dimensions

ItemValue
debit80
credit125.5

The variables change in place. The function itself returns Empty.

Shaded headers are array indices, not data. Quoted cells are text. Values shown are derived from the source, not an Excel execution.

VBA
Sub ExampleExchange()
    Dim a As New Arrays
    Dim debit As Variant, credit As Variant
    Dim ignored As Variant

    debit = 125.5
    credit = 80
    ignored = a.Exchange(debit, credit)
    Debug.Print debit, credit   ' Expected: 80, 125.5
    Debug.Print IsEmpty(ignored) ' Expected: True
End Sub

Behavior and edge cases#

Performance#

Three value assignments. For scalar values, time and auxiliary storage are O(1). Copying array-valued Variants can require work and storage proportional to their contents.

View implementation
VBA
Function Exchange(ByRef val_a, ByRef val_b) As Variant
    'Swaps two values passed by reference

    Dim vTemp       As Variant
    Dim temp        As Variant

    temp = val_b
    val_b = val_a
    val_a = temp
End Function