金曜日, 1月 31, 2025

Excel VBA 38 
Excelで選択したセルをランダムカラーで塗る

 
何の意味も無い処理ですが・・・
Excelで選択したセルをランダムカラーで塗ってみます。

Sub FillCellsWithRandomColors()
Dim rng As Range
Dim cell As Range
Dim randomColor As Long

' 選択範囲を取得
On Error Resume Next
Set rng = Selection
On Error GoTo 0

' 選択範囲がない場合は終了
If rng Is Nothing Then
MsgBox "セル範囲を選択してください。", vbExclamation
Exit Sub
End If

' 範囲内の各セルをランダムな色で塗る
Application.ScreenUpdating = False
For Each cell In rng
' ランダムなRGB値の生成
randomColor = RGB(Int((256) * Rnd), Int((256) * _
            Rnd), Int((256) * Rnd))
    ' セルの塗りつぶし
cell.Interior.Color = randomColor
Next cell
' 画面の更新を一時停止し、処理速度を向上
Application.ScreenUpdating = True

MsgBox "選択したセルをランダムな色で塗りつぶしました。", _
        vbInformation
End Sub


処理したいエリアを選択して実行すれば・・・

こんな感じになります。具体的な用途は謎ですが・・・。