1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VBAメモ: シートに罫線を引くためのコード

Last updated at Posted at 2019-02-26

VBAで動的にシート内容作ってるのに、「印刷したいから罫線引いて」って言われませんか。私は言われます。

「ページ設定でシートの「枠線(G)」にチェックONしてください」では断れない時に、VBAのコード内から罫線引くのに必要な内容をまとめました。

罫線を扱うプロパティ

Range.Borders の各種プロパティ設定すれば、対象範囲に罫線が引ける。
個人的には、LineStyleWeightぐらいを使う。Colorは使う人もいるかもしれない。

参照:Borders (docs.microsoft.com)

With (対象のRange)
    ' ツールバーで罫線引いた時と同じような、普通の線
    .Borders.LineStyle = xlContinuous
    .Borders.Weight = xlThin
    ' 内側は細い線にしとく
    .Borders(xlInsideHorizontal).Weight = xlHairline
    .Borders(xlInsideVertical).Weight = xlHairline
End With

線の場所

単純な Bordersは、範囲内の全部の罫線のこと。
Borders(xlEdgeTop) などと、位置を表す定数を渡すと、一部だけを扱うこともできる。

線の位置 定数 (XlBordersIndex)
上端 xlEdgeTop
下端 xlEdgeBottom
右端 xlEdgeRight
左端 xlEdgeLeft
内側の水平線 xlInsideHorizontal
内側の垂直線 xlInsideVertical

xlbordersindex.png

参照:XlBordersIndex (docs.microsoft.com)

LineStyle: 線の種類

線の種類 定数 (XlLineStyle)
実線 xlContinuous
破線 xlDash
点線 xlDot
線なし xlLineStyleNone

参照: XlLineStyle (docs.microsoft.com)

Weight: 線の太さ

線の太さ 定数 (XlBorderWeight)
細線 xlHairline
普通 xlThin
太い xlMedium
一番太い xlThick

参照:XlBorderWeight (docs.microsoft.com)

罫線を引くメソッド

指定範囲の外周に引数で指定した罫線を引く、BorderAroundというメソッドもあり。
個人的には使用頻度低め。

' ツールバーで罫線引いた時と同じような、普通の線
(対象のRange).BorderAround(xlContinuous, xlThin)

' 冒頭に書いた例を、このメソッド使ってやるなら
With (対象のRange)
    ' 細い線を先に引いておいて
    .Borders.LineStyle = xlContinuous
    .Borders.Weight = xlHairline
    ' 外周を普通線にする
    .BorderAround Weight:=xlThin
End With

参照:Range.BorderAround (docs.microsoft.com)

雑談

あと、「用紙の下いっぱいまで空欄作って」とか言われません?
「そもそも、Excelは帳票印刷ツールじゃない」という言葉は心の中にしまって、レッツ罫線。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?