Thursday 4 November 2010

Excel-lent VBA Range Macro Examples

You learn something new every day. Needed some range examples in Excel - couldn't find some appropriate examples on the internet ... so I created my own. Hope this is helpful to someone. :)

Sub RangeExamples()
Dim r As Range
Set r = Sheet1.Range("E5:G11")
' The range
Debug.Print "The Range: " & r.Address
' Last Column in the range
Debug.Print "Last Column: " & r.Columns(r.Columns.Count).EntireColumn.Address
' First Column in the range
Debug.Print "First Column: " & r.Columns(1).EntireColumn.Address
' First Row in the range
Debug.Print "First Row: " & r.Rows(1).EntireRow.Address
' Last Row in the range
Debug.Print "Last Row: " & r.Rows(r.Rows.Count).EntireRow.Address

' Top-right Cell in the range
Debug.Print "Top-right: " & r.Cells(, r.Columns.Count).Address
' Top-left Cell in the range
Debug.Print "Top-left: " & r.Cells(1).Address
' Bottom-right Cell in the range
Debug.Print "Bottom-right: " & r.Cells(r.Rows.Count, r.Columns.Count).Address
' Bottom-left Cell in the range
Debug.Print "Bottom-left: " & r.Cells(r.Rows.Count, 1).Address

' Intersection of range
Dim r2, r3, r4, r5 As Range
Set r2 = Sheet1.Range("$F:$F")
Set r3 = Intersect(r, r2)
Debug.Print "Intersection is: " & r3.Address

Set r4 = Sheet1.Range("$L:$L")
Set r5 = Union(r4, r3)

' the range between ranges
' between separate columns
Debug.Print Sheet1.Range(Sheet1.Cells(, r3.Column), Sheet1.Cells(, r4.Column)).EntireColumn.Address

' between separate rows
Dim r6, r7 As Range
Set r6 = Sheet1.Rows(10)
Set r7 = Sheet1.Rows(3)

Debug.Print Sheet1.Range(r7.Row & ":" & r6.Row).Address
End Sub