这里可能有一个简单的修复,但是我定义的范围没有被拾取。
我有一个不断发展的数据集,将刷新。当我运行宏时,我想为表的最后5行中的值设置一个范围,以检查Count If
函数的赢/输(在H列中)。但是,当我运行VBA故障排除命令时,范围值从未设置,并且我的公式因运行时错误1004而失败。我已经尝试了Selection.Offset
和ActiveCell.Offset
。
我觉得我犯了一个基本的错误,但可以缩小范围或很容易找到例子来复制
Dim fivegame As Range
Range("H1").Select
Selection.End(xlDown).Select
Set fivegame = Range(Selection.Offset(-4, 0), Selection)
你从哪里得到的错误?这能起作用吗?
Dim fivegame As Range
Set fivegame = Range("H" & Rows.Count).End(xlUp).Offset(-4).Resize(5)
创建对列中最后一个单元格的引用
- 函数
refLastCellsInColumn
将返回对列中最后一个单元格组成的范围的引用,即由提供给NumberOfCells
参数的参数(number)定义的最后一个非空单元格(包括)之上的连续单元格的数量。如果不能创建引用,该函数将返回Nothing
(例如,范围应该从第一个单元格上方的单元格开始…)。
代码
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