土曜日, 9月 06, 2025

Excel VBA 52 
Excelで選択したセルの罫線を自動生成

選択したセルの罫線(格子+太い外枠)と1行目のセルの塗りつぶしを自動生成します。

Sub SetGridWithBoldBorderAndFill()
Dim rng As Range
Dim border As Variant
Dim firstRow As Range
Dim colorDialog As Object
Dim chosenColor As Long
' 選択範囲を取得
Set rng = Selection
' 格子状の罫線を設定
rng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
rng.Borders(xlInsideHorizontal).Weight = xlThin
rng.Borders(xlInsideVertical).LineStyle = xlContinuous
rng.Borders(xlInsideVertical).Weight = xlThin
' 外枠を太枠に設定
For Each border In Array(xlEdgeLeft, xlEdgeRight, _
xlEdgeTop, xlEdgeBottom)
With rng.Borders(border)
.LineStyle = xlContinuous
.Weight = xlThick
End With
Next border

' 最初の行を取得
Set firstRow = rng.Rows(1)

' カラーダイアログを表示し、ユーザーに色を選択させる
Set colorDialog = Application.Dialogs(xlDialogEditColor)
If colorDialog.Show(1) Then
chosenColor = ActiveWorkbook.Colors(1)
firstRow.Interior.Color = chosenColor
End If
End Sub

データの有無に関係なく・・・

任意のセルを選択して実行すると・・・

選択した範囲の一行目の塗りつぶしの色を要求してくるので設定すれば・・・

全体は格子、太線の外枠で選択した範囲の一行目の塗りつぶしが完了します。