Kazuki.io

プログラミングやITガジェットなどの備忘録だよ。人の役に立てばいいな。

VBA セル選択範囲を取得する

VBAでセルの選択範囲に対する処理を行うことが多々あったので、セルの選択範囲から行番号と列番号を取得するコードをメモしておく

'フィルタ後に表示されている行を表示
    Dim i As Integer, j As Integer, k As Long
    Dim rang As Range
    Dim member() As Long
    '列の位置はB固定になっているので、ここを変える
    ReDim member(Range("B1", Range("B" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible).Count)
    
    For Each rang In Range("B1", Range("B" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible).Rows
        member(i) = rang.Row
        i = i + 1
    Next rang
    
    With Selection
    For i = 1 To .Areas.Count
    For j = 1 To .Areas(i).Rows.Count
    Dim selectedCells As Range
    Set selectedCells = .Areas(i).Rows(j)

    For k = 0 To UBound(member)
    If member(k) = selectedCells.Row Then         
        Dim r As Long: r = selectedCells.Row
        Dim c As Long: c = selectedCells.Column
        Debug.Print "Row:" & r & " Col:" & c
        'ここに処理を書く
                        
                        
    End If
    Next k
    Next j
    Next i
    End With