You can pass a worksheet and a named range that's in it to this sub and it will print the range's address and first Column
and first Row
to the Immediate Window. If the range is more than one cell, it will also print the last column and row:
Sub PrintNameRowAndCol(ws As Excel.Worksheet, strName As String)
Dim rng As Excel.Range
Dim SplitAddress As Variant
On Error Resume Next
Set rng = ws.Range(strName)
On Error GoTo 0
If Not rng Is Nothing Then
Debug.Print rng.Address
SplitAddress = Split(rng.Address, "$")
Debug.Print "Column: "; SplitAddress(1)
Debug.Print "Row: "; SplitAddress(2)
If rng.Cells.Count > 1 Then
Debug.Print "Last Column: "; SplitAddress(3)
Debug.Print "Last Row: "; SplitAddress(4)
End If
End If
End Sub
If there is no range with that name, nothing happens.
The routine uses the Split
function which breaks a string into an array based on a delimiter, "$" in this case. Since the Range's Address
property returns a string in the absolute reference format, i.e., $Column$Row, the Split function always returns an array with two elements, the column and row, for a single-cell range. For a multiple cell range it returns four elements.
Call it like this:
Sub test()
PrintNameRowAndCol ActiveSheet, "Candy"
End Sub
EDIT: In answer to your specific question in the comments, you don't really need to figure the column letters and row numbers of the two ranges. In order to get the contents of the intersection of the column of one range and the row of another, and then assign it to a 3rd range, do something like this:
With ActiveSheet
.Range("D12") = .Cells(.Range("Cost").Row, .Range("Candy").Column)
End With