randomise rows in VBA

后端 未结 3 1061
离开以前
离开以前 2021-01-26 16:53

so i have an excel file with multiple columns and rows. At the moment it looks like this:

  | A  | B  | C  | D  
---------------------
1 | 1a | 1b | 1c | 1d 
---         


        
3条回答
  •  逝去的感伤
    2021-01-26 17:35

    I'd go like follows:

    Sub ShuffleRows()
        Dim vals As Variant, val As Variant
        Dim iRow As Long
    
        With Range("A1").CurrentRegion '<--| reference your contiguous range 
            vals = .Value '<--| store its content in an array
            For Each val In GetRandomNumbers(.Rows.count) '<--| loop through referenced range shuffled rows indexes
                iRow = iRow + 1 '<--| update current row to write in counter
                .Rows(iRow).Value = Application.Index(vals, val, 0) '<--| write in current rows to write the random row from corresponding shuffled rows indexes
            Next
        End With
    End Sub
    
    Function GetRandomNumbers(ByVal n As Long) As Variant
        Dim i As Long, rndN As Long, tempN As Long
    
        ReDim randomNumbers(1 To n) As Long '<--| resize the array to the number of rows
        For i = 1 To n '<--| fill it with integer numbers from 1 to nr of rows
            randomNumbers(i) = i
        Next
    
        'shuffle array
        Do While i > 2
            i = i - 1
            Randomize
            rndN = Int(i * Rnd + 1)
            tempN = randomNumbers(i)
            randomNumbers(i) = randomNumbers(rndN)
            randomNumbers(rndN) = tempN
        Loop
        GetRandomNumbers = randomNumbers
    End Function
    

提交回复
热议问题