Sorting a vector in Excel VBA

回眸只為那壹抹淺笑 提交于 2021-02-08 04:29:15

问题


I'm VERY new to Excel VBA. I want to write a function that offsets the cells in the current vector (the range selected by the user) by an amount also specified by the user.

The cells must be moved up out of the array by "n", and must then be displayed at the bottom of the same array after the remaining cells have moved up to take the place of the cells shifted up and out of the array.

Any advice will be greatly appreciated, the current code I wrote is not working and I know too little to help myself.

Many thanks!

Function ShiftVector(rng As Range, n As Integer)
    'User selects a vector and inputs an integer.
    'The vector must be sorted upwards by the amount equal to the entered integer

    Dim i As Integer, rw As Integer, temp As Variant

    rw = rng.rows.Count

    ReDim b(1 To rw) As Variant
    ReDim temp(1 To n) As Variant

    b = rng
    For i = 1 To n
        temp = b(i)
        'move the data in cells i=1 to n to the temporary array
    Next i

    b(i) = rng.Offset(-n, 0)
    'move the cells in array b up by n

    For i = rw - n To nr
        b(i) = temp
        i = i + 1

        'I'm not sure if this is correct: I want to replace the top shifted cells
        'back into the bottom of array b
     Next i
     ShiftVector4 = b

     'The function must output the newly assembled array b where
     'the top cells that were moved up n-spaces are now wrapped
     'around and are shown at the bottom of the array b
 End Function

回答1:


Something like this should work:

Sub Tester()
    ShiftUp Range("B4:C13"), 3
End Sub


Sub ShiftUp(rng As Range, numRows As Long)
    Dim tmp
    With rng
        tmp = .Rows(1).Resize(numRows).Value
        .Rows(1).Resize(.Rows.Count - numRows).Value = _
          .Rows(numRows + 1).Resize(.Rows.Count - numRows).Value
        .Rows((.Rows.Count - numRows) + 1).Resize(numRows).Value = tmp
    End With
End Sub

As a UDF:

Function ShiftUp(rng As Range, numRows As Long)
    Dim d, dOut, r As Long, c As Long, rMod As Long, rTot As Long
    Dim break As Long
    d = rng.Value
    dOut = rng.Value 'as a shortcut to creating an empty array....
    rTot = UBound(d, 1)
    break = rTot - numRows
    For r = 1 To rTot
        For c = 1 To UBound(d, 2)
            'figure out which input row to use...
            rMod = IIf(r <= break, r + numRows, -(break - r))
            dOut(r, c) = d(rMod, c)
        Next c
    Next r
    ShiftUp = dOut
End Function

Note this is an array formula, so you will need to select a range the same size as the input range and enter the formula using CtrlShiftEnter



来源:https://stackoverflow.com/questions/53142302/sorting-a-vector-in-excel-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!