0
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]ExcelのRangeが同じ範囲を参照しているかを判定する関数

Last updated at Posted at 2017-10-02

ExcelのRangeオブジェクトが同じ範囲を参照しているかの確認が面倒だったため、判定用の関数を作成してみました。

コード

'iRng1とiRng2が同じ範囲を参照しているかを判定する関数。
Function RangeEqual(ByVal iRng1 As Excel.Range, ByVal iRng2 As Excel.Range) As Boolean
    Let RangeEqual = (iRng1.Address(External:=True) = iRng2.Address(External:=True))
End Function

ポイント

引数未指定のAddressプロパティでは「$A$1」などの形式となり、ワークシートの違いなどを判定できません。

第4引数のExternalを指定することで

[ブック名]シート名!$A$1

のような形式となり、ワークシートが違う場合なども判定できるようになります。

サンプル


Sub Sample_RangeEqual()
    
    'Trueの場合
    '単一セル
    Debug.Print RangeEqual(ActiveCell, ActiveCell)
    Debug.Print RangeEqual(ActiveCell, ActiveCell.Offset(0, 0))
    
    'セル範囲
    Debug.Print RangeEqual(Cells, Cells)
    Debug.Print RangeEqual(Rows, Columns)
    
    With Excel.Application
        '複数のセル
        Debug.Print RangeEqual(.Union(.Range("A1"), .Range("B2")), .Union(.Cells(1, 1), .Cells(2, 2)))
    End With 'Excel.Application
    
    'Falseの場合
    Debug.Print RangeEqual(ActiveCell, ActiveCell.Offset(1, 0))
    
End Sub
0
1
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
0
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?