例文を使って繰り返し業務を時短

【マクロ・VBA】指定した範囲のデータを乱数で並び替える

エクセル、マクロ、VBAで指定した範囲のデータを乱数で並び替える方法 VBA

乱数で並び替え

Sub 乱数で並び替え()

Dim i
Randomize

For i = 1 To ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Cells(i, 7).Value = Int(5000 * Rnd(1)) + 1
Next i

'---------------
Dim my_array As Variant
Dim s_row, s_col As Long
Dim max_row, max_col As Long

s_row = 1
s_col = 1

max_row = ThisWorkbook.ActiveSheet.Cells(Rows.Count, s_col).End(xlUp).Row
max_col = ThisWorkbook.ActiveSheet.Cells(s_row, Columns.Count).End(xlToLeft).Column

Set my_array = Range(Cells(s_row, s_col), Cells(max_row, max_col))

my_array.Select

Selection.AutoFilter Field:=1
'----------
ActiveSheet.Range("G1").Sort key1:=ActiveSheet.Range("G1"), order1:=xlAscending, Header:=xlYes

MsgBox "完了"
End Sub

乱数で並び替え(もとの順番と乱数時の数値を表記)

Sub 乱数で並び替え_もとの順番表記と乱数時の順番表記()

Dim s_row, s_col As Long
Dim max_row, max_col As Long

s_row = 1
s_col = 1

max_row = ThisWorkbook.ActiveSheet.Cells(Rows.Count, s_col).End(xlUp).Row
max_col = ThisWorkbook.ActiveSheet.Cells(s_row, Columns.Count).End(xlToLeft).Column

Dim i

'-------------
Dim 連番
連番 = 1
 For i = 2 To max_row
   Cells(i, max_col + 1).Value = 連番
   連番 = 連番 + 1
 Next

Cells(1, max_col + 1) = "もとの順番"

'------------

Randomize

For i = 2 To ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Cells(i, max_col + 2).Value = Cells(i, max_col + 1).Value * Int(5000 * Rnd(1)) + 1

'Cells(i, max_col + 1).Value = Int(5000 * Rnd(1)) + 1

Next i

Cells(1, max_col + 2) = "RANDAM"
'-------------

Dim my_array As Variant
Set my_array = Range(Cells(s_row, s_col), Cells(max_row, max_col))

my_array.Select

Selection.AutoFilter Field:=1
'----------
ActiveSheet.Range("G1").Sort key1:=ActiveSheet.Range("G1"), order1:=xlAscending, Header:=xlYes

MsgBox "完了"
End Sub

コメント

タイトルとURLをコピーしました