flexinau said:how can it be written in VBA where I want to name a range where the row number is variable.
flexinau said:In my case, the row number should be the last row.
ps The data is contained in a column.
flexinau said:Hi,
Please, how can it be written in VBA where I want to name a range where the row number is variable. In my case, the row number should be the last row.
ps The data is contained in a column.
Thanks
Option Explicit
Function InUseColRange(RefCell As Range) As Range
Dim TopCell As Range, LastCell As Range
With RefCell.Parent
Set TopCell = .Cells(1, RefCell.Column)
If IsEmpty(TopCell) Then Set TopCell = TopCell.End(xlDown)
If TopCell.Address = .Cells(Rows.Count, RefCell.Column).Address Then
Set InUseColRange = Nothing
Else
Set LastCell = .Cells(Rows.Count, RefCell.Column).End(xlUp)
Set InUseColRange = Range(TopCell, LastCell)
End If
End With
End Function
Sub testit()
On Error Resume Next
MsgBox TypeName(InUseColRange(Range("a1"))): MsgBox InUseColRange(Range("a1")).Address
MsgBox TypeName(InUseColRange(Range("s1"))): MsgBox InUseColRange(Range("s1")).Address
End Sub
Set myRange = Application.InputBox(prompt:="Enter K6:K" & LastRow, Type:=8)
NameOfRange = "POC"
ActiveSheet.Protection.AllowEditRanges.Add Title:=NameOfRange, Range:=myRange
For a programmatic solution, useCode:Option Explicit Function InUseColRange(RefCell As Range) As Range Dim TopCell As Range, LastCell As Range With RefCell.Parent Set TopCell = .Cells(1, RefCell.Column) If IsEmpty(TopCell) Then Set TopCell = TopCell.End(xlDown) If TopCell.Address = .Cells(Rows.Count, RefCell.Column).Address Then Set InUseColRange = Nothing Else Set LastCell = .Cells(Rows.Count, RefCell.Column).End(xlUp) Set InUseColRange = Range(TopCell, LastCell) End If End With End Function Sub testit() On Error Resume Next MsgBox TypeName(InUseColRange(Range("a1"))): MsgBox InUseColRange(Range("a1")).Address MsgBox TypeName(InUseColRange(Range("s1"))): MsgBox InUseColRange(Range("s1")).Address End Sub