2
2

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.

Excel VBAでマウスでポチポチと選択できる表を作る

Last updated at Posted at 2020-02-19

概要

クリックやドラッグで選択してるっぽく見える表をマクロで作る。
見えるだけで内部で何かデータを保持するわけではない。

select.jpg

コード

Sheet1
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Const ROW_START As Long = 3         '表のデータが始まる行
    Const COL_START As Long = 2         '     "      始まる列
    Const COL_END As Long = 4           '     "      終わる列
    Const COLOR_OFF As Long = &HFFFFFF  '非選択状態のセルの色
    Const COLOR_ON As Long = 14083324   '選択状態のセルの色
    Const COL_SELECT As Long = 2        '選択状態かどうかの値を入れる列
    Const COL_TARGET As Long = 3        '最終行を取得するための列
    
    '表の外なら何もせずに終了
    If Target.Row + Target.Rows.Count - 1 < ROW_START Then Exit Sub
    If Target.Column + Target.Columns.Count - 1 < COL_START Then Exit Sub
    If COL_END < Target.Column Then Exit Sub
    
    With Sheet1
        '表の最終行より下なら終了
        Dim lr As Long
        lr = .Cells(.Rows.Count, COL_TARGET).End(xlUp).Row
        If Target.Row > lr Then Exit Sub
        
        '反転させる行を特定
        Dim sr As Long
        Dim er As Long
        sr = WorksheetFunction.Max(Target.Row, ROW_START)
        er = WorksheetFunction.Min(Target.Row + Target.Rows.Count - 1, lr)
            
        '反転
        If .Cells(sr, COL_TARGET).Interior.Color <> COLOR_OFF Then
            .Range(.Cells(sr, COL_START), .Cells(er, COL_END)).Interior.Color = COLOR_OFF
            .Range(.Cells(sr, COL_SELECT), .Cells(er, COL_SELECT)).Value = ""
        Else
            .Range(.Cells(sr, COL_START), .Cells(er, COL_END)).Interior.Color = COLOR_ON
            .Range(.Cells(sr, COL_SELECT), .Cells(er, COL_SELECT)).Value = "v"
        End If
    End With
End Sub

その他

名簿とかからGUIな感じで選択してもらう時にちょうどいい。
添付写真の「選択」列は、フォントを"Magneto"にして「v」をチェックマークっぽく見えるように一工夫。

2
2
2

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?