randomise rows in VBA

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

    This is my solution:

    First I have created a function to generate random numbers between a and b without repeated values:

    jlqmoreno@gmail.com

    Julio Jesus Luna Moreno

    Option Base 1
    Public Function u(a As Variant, b As Variant) As Variant
     Application.Volatile
     Dim k%, p As Double, flag As Boolean, x() As Variant
        k = 1
      flag = False
      ReDim x(1)
       x(1) = Application.RandBetween(a, b)
      Do Until k = b - a + 1
    
       Do While flag = False
       Randomize
        p = Application.RandBetween(a, b)
         'Debug.Assert p = 2
        resultado = Application.Match(p, x, False)
         If IsError(resultado) Then
          k = k + 1
          ReDim Preserve x(k)
          x(k) = p
           flag = True
          Else
           flag = False
          End If
       Loop
       flag = False
      Loop
      u = x
    End Function
    

    this is nessesary since i needed a funtion to create random indices with no duplicates (This was the rough part) Then i used this function using the logic i applied here

    with this function:

    Public Function RNDORDER(rango As Range) As Variant
     Dim z() As Variant, n%, m%, i%, j%, y() As Variant, k%
      n = rango.Rows.count
      m = rango.Columns.count
      k = 1
       ReDim x(n, m)
       ReDim y(n)
        y = u(1, n)
       For i = 1 To n
         For j = 1 To m
         x(i, j) = rango(y(i), j)
         Next j
     Next i
    
       RNDORDER = x   
    

    Just run this function as an array function.

    Thanks!

提交回复
热议问题