
表を自動でフォーマットする Excel2013マクロ講座 64回
今回は、アクティブセルのある範囲に対して、表のデザインをするというマクロです。
使うのは、何度も登場しているCurrentRegion プロパティです。
CurrentRegionプロパティは、空白のセルで囲まれた範囲を読み取り、Range オブジェクトを返します。
また同じ対象(オブジェクト)に対して、繰り返し処理をする時に、記述を簡単にする、
With...End With Statement も使います。
(サンプルファイルは、こちらから マクロ64回サンプルデータ)


Sub セルのある表デザイン()
With ActiveCell.CurrentRegion
With .Borders ' 表全体の設定
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = 16
End With
With .Rows(1) ' タイトル行の設定
.Interior.ColorIndex = 37
.HorizontalAlignment = xlCenter
.Borders(xlEdgeTop).Weight = xlMedium ' 上罫線を中太
.Borders(xlEdgeBottom).Weight = xlMedium ' 下罫線を中太に
End With
End With
End Sub


.SpecialCells(Type:=xlCellTypeConstants, Value:=xlNumbers).NumberFormat = "#,##0_ "
全く同じではつまらないので、タイトル行の色を変更しています。
Sub セルのある表デザインと書式()
With ActiveCell.CurrentRegion
With .Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = 16
End With
With .Rows(1)
.Interior.ColorIndex = 23
.HorizontalAlignment = xlCenter
.Font.Color = vbWhite ' フォントの色を白に
End With
On Error Resume Next ' エラーを無視する
.SpecialCells(Type:=xlCellTypeConstants, Value:=xlNumbers).NumberFormat = "#,##0_ "
End With
End Sub