关于Chip Pearson的ReverseArrayInPlace函数,用户如何在第一时间将一个数组传递给输入函数?

问题描述 投票:-1回答:1

为了学习如何反转一个一维数组,几个谷歌搜索都指向 Chip Pearson 的 ReverseArrayInPlace 函数 (见这里) http:/www.cpearson.comexcelvbaarrays.htm).

For Ndx = LBound(InputArray) To ((UBound(InputArray) - LBound(InputArray) + 1) \ 2)
'swap the elements
Temp = InputArray(Ndx)
InputArray(Ndx) = InputArray(Ndx2)
InputArray(Ndx2) = Temp
' decrement the upper index
Ndx2 = Ndx2 - 1
Next Ndx

然而,作为一个非常新手的vba编码员,我对两件事感到困惑。

  1. 用户如何将一个特定的范围传递给InputArray?
  2. 用户如何将反转的数组打印到工作表中?他们会简单地打印Temp数组吗?
arrays excel vba reverse
1个回答
1
投票

这是整个函数(减去检查数组尺寸的部分)。

它需要一个参数是一个数组,它也可以接受一个可选的布尔值。

Public Function ReverseArrayInPlace(InputArray As Variant, _
    Optional NoAlerts As Boolean = False) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ReverseArrayInPlace
' This procedure reverses the order of an array in place -- this is, the array variable
' in the calling procedure is reversed. This works only on single-dimensional arrays
' of simple data types (String, Single, Double, Integer, Long). It will not work
' on arrays of objects. Use ReverseArrayOfObjectsInPlace to reverse an array of objects.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim Temp As Variant
Dim Ndx As Long
Dim Ndx2 As Long


'''''''''''''''''''''''''''''''''
' Set the default return value.
'''''''''''''''''''''''''''''''''
ReverseArrayInPlace = False

'''''''''''''''''''''''''''''''''
' ensure we have an array
'''''''''''''''''''''''''''''''''
If IsArray(InputArray) = False Then
    If NoAlerts = False Then
        MsgBox "The InputArray parameter is not an array."
    End If
    Exit Function
End If



Ndx2 = UBound(InputArray)
''''''''''''''''''''''''''''''''''''''
' loop from the LBound of InputArray to
' the midpoint of InputArray
''''''''''''''''''''''''''''''''''''''
For Ndx = LBound(InputArray) To ((UBound(InputArray) - LBound(InputArray) + 1) \ 2)
    'swap the elements
    Temp = InputArray(Ndx)
    InputArray(Ndx) = InputArray(Ndx2)
    InputArray(Ndx2) = Temp
    ' decrement the upper index
    Ndx2 = Ndx2 - 1
Next Ndx

''''''''''''''''''''''''''''''''''''''
' OK - Return True
''''''''''''''''''''''''''''''''''''''
ReverseArrayInPlace = True

End Function

这个子将调用反转函数。

Sub test()
    Dim arr(20) As Long
    Dim i As Long

    For i = 0 To 20

        arr(i) = i
        Debug.Print arr(i)
    Next
    Dim success As Boolean
    success = ReverseArrayInPlace(arr)
    Debug.Print success
    For i = 0 To 20
        Debug.Print arr(i)
    Next
End Sub

由于数组默认是通过引用传递的,所以原始数组已经被修改,不需要返回。

© www.soinside.com 2019 - 2024. All rights reserved.