There's probably a simple fix here, but my defined range is not being picked up.
I have an evolving set of data that will refresh. When I run the macro, I want to set a range for the values in the last 5 rows of the table to check win / loss (in column H) for a Count If
function. But when I run the VBA trouble shoot command, a range value never gets set and my formula fails for Run-time error 1004. I've tried with both Selection.Offset
and ActiveCell.Offset
.
I feel like I'm making a basic mistake, but can narrow it down or easily find examples here to replicate
Dim fivegame As Range
Range("H1").Select
Selection.End(xlDown).Select
Set fivegame = Range(Selection.Offset(-4, 0), Selection)
Where do you get the error? Does this work?
Dim fivegame As Range
Set fivegame = Range("H" & Rows.Count).End(xlUp).Offset(-4).Resize(5)
refLastCellsInColumn
will return a reference to the range consisting of the last cells in a column ie the number of consecutive cells above the last non-empty cell (incl.) defined by the parameter (number) supplied to the NumberOfCells
argument. The function will return Nothing
if the reference cannot be created (eg the range is supposed to start with a cell above the first cell...).The Code
Option Explicit
Sub HowToUseItInYourProcedure()
Dim fivegame As Range
Set fivegame = refLastCellsInColumn(Range("H1"), 5)
End Sub
Function refLastCellsInColumn( _
ByVal FirstCell As Range, _
Optional ByVal NumberOfCells As Long = 1, _
Optional ByVal allowLessCells As Boolean = False) _
As Range
If Not FirstCell Is Nothing And NumberOfCells > 0 Then
With FirstCell
Dim rg As Range
Set rg = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If Not rg Is Nothing Then
If rg.Row - .Row >= NumberOfCells - 1 Then
Set refLastCellsInColumn = _
rg.Offset(1 - NumberOfCells).Resize(NumberOfCells)
Else
If allowLessCells Then
Set refLastCellsInColumn = .Resize(rg.Row - .Row + 1)
End If
End If
End If
End With
End If
End Function
Sub refLastCellsInColumnTEST()
Const FirstCellAddress As String = "H1"
Const NumberOfCells As Long = 2000000
' Define First Cell Range.
Dim cel As Range: Set cel = Range("H1")
' Define Last Cells in column.
Dim rg As Range: Set rg = refLastCellsInColumn(cel, NumberOfCells, True)
' Test.
If Not rg Is Nothing Then
Debug.Print rg.Address
Else
Debug.Print "Nope"
End If
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.