トップ > 汎用コード > 選択セル範囲の値をランダムに入れ替える

選択セル範囲の値をランダムに入れ替える2010.06.10

選択しているセル範囲の値をランダムに入れ替えるコードを紹介します。数値だけでなく文字列にも対応しています。席替えやグループ決めなどに利用できるかもしれません。


【お薦め】マクロ・プロシージャを管理する無料のツール!
 Excelマクロ管理ツール

サンプルコード2010.06.10

コードの貼り付け場所

・セル範囲を選択していないと、マクロは動作しません。
・選択しているセルが単一の場合、マクロは動作しません。

Sub Rand_2() '選択しているセル範囲内の値をランダムに入れ替える
    If TypeName(Selection) <> "Range" Then Exit Sub
    '連想配列の作成
    Dim myDic  As Object
    Set myDic = CreateObject("Scripting.Dictionary")
    
    Dim varRes As Variant
    Dim varKey As Variant
    Dim lngRnd As Long
    Dim c      As Long
    Dim i      As Long
    Dim j      As Long
    With Selection
        If 1 < .Areas.Count Or .Cells.Count = 1 Then Exit Sub
        varRes = .Value '選択セル範囲の値を変数に代入
        Randomize
        Do
            lngRnd = Int(.Cells.Count * Rnd()) + 1  '1~選択範囲のセル個数間のランダム値取得
            If Not myDic.Exists(lngRnd) Then        'ランダム値が初出なら処理を行う
                c = c + 1        'Keyにランダム値、Itemにランダム値を基に取得したデータを追加
                myDic.Add lngRnd, .Cells(lngRnd).Value
            End If
        Loop Until c = .Cells.Count
        varKey = myDic.Keys
        For i = 1 To .Rows.Count
            For j = 1 To .Columns.Count        'Keyのランダム値を基に変数内でデータ入れ替え
                varRes(i, j) = myDic.Item(varKey((i - 1) * .Columns.Count + j - 1))
            Next
        Next
        .Value = varRes '変数の値を選択セル範囲に代入
    End With
End Sub


ページトップへ戻る

Excel 汎用コード

Copyright(C) 2009- 坂江 保 All Rights Reserved.