[AccessD] Swap two elements in an array

Paul Wolstenholme Paul.W at industrialcontrol.co.nz
Thu Aug 25 22:58:03 CDT 2022


You could also have written it like this:
Function SwapValues( ByRef X As Variant,  ByRef Y As Variant  ) As Boolean
    Dim temp As Variant
    temp = X
    X = Y
    Y = temp
    SwapValues = True
End Function

And called it like this:
b = SwapValues( myArray(n1), myArray(n2) )

I would expect this version is likely to be compiled as faster code (fewer
parameters, fewer array lookups and the possibility of those array lookups
being based partially or wholly on expressions the compiler can evaluate to
constants).  It also allows the function to be used with any pair of
variables - not just array elements.

By specifying 'ByRef' and 'Variant', despite them being defaults, I have
indicated that I have considered the alternatives and made a deliberate
choice.  It wasn't coded with undue haste or left to be reviewed later.


On Fri, 26 Aug 2022 at 11:19, Stuart McLachlan <stuart at lexacorp.com.pg>
wrote:

> On 25 Aug 2022 at 8:52, Arthur Fuller wrote:
> > Function SwapElements(ByRef a As Variant, nPos1 As Integer, nPos2 As
> > Integer) _
> >         As Boolean
> >     Dim temp As Integer
> >     temp = a(nPos1)
> >     a(nPos1) = a(nPos2)
> >     a(nPos2) = temp
> >     SwapElements = True
> > End Function
>
> So what happens if a is an array of strings?  :)
> As I said in my original reply:
> "If you define Temp as a Variant, you can use it with any type of array."
>
> Incidentally ByRef and As Variant are defaults, so you could just use:
>
> Function SwapElements(a, nPos1 As Long, nPos2 As Long) As Boolean
>
>
>
>
> --
> AccessD mailing list
> AccessD at databaseadvisors.com
> https://databaseadvisors.com/mailman/listinfo/accessd
> Website: http://www.databaseadvisors.com
>


More information about the AccessD mailing list