Normally at work whenever we want to swap the value of two variables, we
use code similar to the following:

Dim TempVar
TempVar = VariableX
VariableX = VariableY
VariableY = TempVar

Is there anything out there that will do this in an elegant, one-line
approach?

e.g.: Swap(VariableX,VariableY)

I realize you could probably build a function easy enough but I don't
want to recreate the wheel if I don't have to.

Cheers,
Scott

Re: Swapping Variables (without a temp variable) by David

David
Fri May 28 22:43:21 CDT 2004

Scott McNair wrote:
> Normally at work whenever we want to swap the value of two variables, we
> use code similar to the following:
>
> Dim TempVar
> TempVar = VariableX
> VariableX = VariableY
> VariableY = TempVar
>
> Is there anything out there that will do this in an elegant, one-line
> approach?
>
> e.g.: Swap(VariableX,VariableY)
>
> I realize you could probably build a function easy enough but I don't
> want to recreate the wheel if I don't have to.
>
> Cheers,
> Scott
You've done all the work already.

sub SWAP(byref v1,byref v1 )
temp = v1
v1=v2
v2=temp
end sub

remember that if you use a function, you MUST pass the arguments by
reference, or you only trade the values within the function, once you
leave the variables resume the initial values.

Re: Swapping Variables (without a temp variable) by Ross

Ross
Sun Jun 06 21:50:34 CDT 2004

Scott McNair <scott.mcnair@sfmco.takethispartout.com> wrote in
news:Xns94F58603A7758sfmco@207.46.248.16:

> Normally at work whenever we want to swap the value of two variables,
we
> use code similar to the following:
>
> Dim TempVar
> TempVar = VariableX
> VariableX = VariableY
> VariableY = TempVar
>
> Is there anything out there that will do this in an elegant, one-line
> approach?
>
> e.g.: Swap(VariableX,VariableY)
>
> I realize you could probably build a function easy enough but I don't
> want to recreate the wheel if I don't have to.
>
> Cheers,
> Scott

Well, it ain't elegant and it ain't one-line, but if you know your
variables contain strings, this can avoid the extra temp variable:

VariableY = VariableY & VariableX
VariableX = left(VariableY, len(VariableY) - len(VariableX))
VariableY = mid(VariableY, len(VariableX)+1)

Or, if you know your variables contain integers, you can use XOR to avoid
the extra temp variable:

X = X XOR Y
Y = X XOR Y
X = X XOR Y