randomise rows in VBA

后端 未结 3 1085
离开以前
离开以前 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

    It's true that this question has many possible answers. This is probably the most lame one, but it works quite ok actually:

    1. Add an additional column;
    2. Then put random value in this column;
    3. Sort by this column - that's exactly what you want!
    4. Delete the additional column, so the trick is no visible!
    5. Voila!

    Just to give you some idea how this should look like:

    Option Explicit
    
    Public Sub Randomize()
    
        Dim lCounter    As Long
    
        Application.ScreenUpdating = False
        Columns("A:A").Insert Shift:=xlToRight
    
        For lCounter = 1 To 5
            Cells(lCounter, 1) = Rnd()
        Next lCounter
    
        With ActiveSheet.Sort
            .SortFields.Add Key:=Range("A1:A5")
            .SetRange Range("A1:E5")
            .Apply
        End With
    
        Columns("A:A").Delete
        Application.ScreenUpdating = False
    
    End Sub
    

    It would work on data like this one:

    You can further update the code, by removing the magic numbers and improving the ranges.

提交回复
热议问题