获取实际使用的范围
我有一个Excel工作表,有一个button。
当我调用usedRange()函数时,它返回的范围包括button部分。
无论如何,我可以得到包含数据的实际使用的范围?
什么样的button,既不是一个窗体控件,也不是一个ActiveX控件应该影响使用的范围。
excel不能很好地logging使用的范围是一个已知的问题。 通过VBA对使用范围的任何引用都会将该值重置为当前使用的范围。 所以试试运行这个子程序:
Sub ResetUsedRng() Application.ActiveSheet.UsedRange End Sub
如果没有,你可能会有一些格式化的问题。 尝试清除/删除最后一行之后的所有单元格。
关于上面还看到:
Excel开发人员提示
另一种find最后使用的单元格的方法:
Dim rLastCell As Range Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
更改search方向以查找第一个使用的单元格。
重新编写了一个非常完整的答案。 但是,我想添加End
语句,您可以使用:
find最后一个使用的单元格,在列中的空白之前:
Sub LastCellBeforeBlankInColumn() Range("A1").End(xldown).Select End Sub
在列中查找最后使用的单元格:
Sub LastCellInColumn() Range("A" & Rows.Count).End(xlup).Select End Sub
在一行的空白处find最后一个单元格:
Sub LastCellBeforeBlankInRow() Range("A1").End(xlToRight).Select End Sub
查找行中最后使用的单元格:
Sub LastCellInRow() Range("IV1").End(xlToLeft).Select End Sub
在这里看到更多的信息(和解释为什么xlCellTypeLastCell
不是很可靠)。
这里有一对函数返回基于上面的Reafidy解决scheme的工作表的最后一行和列。
Function LastRow(ws As Object) As Long Dim rLastCell As Object On Error GoTo ErrHan Set rLastCell = ws.Cells.Find("*", ws.Cells(1, 1), , , xlByRows, _ xlPrevious) LastRow = rLastCell.Row ErrExit: Exit Function ErrHan: MsgBox "Error " & Err.Number & ": " & Err.Description, _ vbExclamation, "LastRow()" Resume ErrExit End Function Function LastCol(ws As Object) As Long Dim rLastCell As Object On Error GoTo ErrHan Set rLastCell = ws.Cells.Find("*", ws.Cells(1, 1), , , xlByColumns, _ xlPrevious) LastCol = rLastCell.Column ErrExit: Exit Function ErrHan: MsgBox "Error " & Err.Number & ": " & Err.Description, _ vbExclamation, "LastRow()" Resume ErrExit End Function
Public Sub FindTrueUsedRange(RowLast As Long, ColLast As Long) Application.EnableEvents = False Application.ScreenUpdating = False RowLast = 0 ColLast = 0 ActiveSheet.UsedRange.Select Cells(1, 1).Activate Selection.End(xlDown).Select Selection.End(xlDown).Select On Error GoTo -1: On Error GoTo Quit Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Activate On Error GoTo -1: On Error GoTo 0 RowLast = Selection.Row Cells(1, 1).Activate Selection.End(xlToRight).Select Selection.End(xlToRight).Select Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Activate ColLast = Selection.Column Quit: Application.ScreenUpdating = True Application.EnableEvents = True On Error GoTo -1: On Error GoTo 0 End Sub
我使用以下vba代码来确定工作表的整个使用行范围,然后缩短列的选定范围:
Set rUsedRowRange = Selection.Worksheet.UsedRange.Columns( _ Selection.Column - Selection.Worksheet.UsedRange.Column + 1)
也可以用另一种方式工作:
Set rUsedColumnRange = Selection.Worksheet.UsedRange.Rows( _ Selection.Row - Selection.Worksheet.UsedRange.Row + 1)