[英]Trying to select last row and column in VBA
我在此问题上停留了最长时间,这可能是我所没有看到的简单解决方法。 我正在尝试选择表格的最后一行,并围绕它创建边框直到最后一列。 “ POS”是我正在工作的工作表的名称。“ BRangePOS”是我说这是表格的起点。
这是我的代码。
Set BRangePOS = POS.Range("A1")
With BRangePOS
With POS
lrowPOS = .Cells(.Rows.Count, 1).End(xlUp).Row
lcolPOS = .Cells(1, Columns.Count).End(xlToLeft).Column
End With
End With
POS.Range(lrowPOS, lcolPOS).BorderAround Weight:=xlMedium
我得到的错误是“对象_工作表的方法'范围'失败”
任何帮助都会很棒。
谢谢,
G
也许您可以从中得到一些想法。 要查找最后一行:
lastRow = findLastRow("Sheet1", "A:A") ' Or "A:X"
Function findLastRow(Sheetname As String, ColumnName As String) As Integer
Dim lastRow As Integer
Dim r As Range
Dim WS As Worksheet
Set WS = Worksheets(Sheetname)
lastRow = WS.UsedRange.Rows.Count
'*
'* Search backwards till we find a cell that is not empty
'*
Set r = WS.Range(ColumnName).Rows(lastRow)
While IsEmpty(r)
Set r = r.Offset(-1, 0)
Wend
lastRow = r.Row
Set WS = Nothing
findLastRow = lastRow
End Function
如果需要,为列添加功能
要在表格的最后一行周围创建边框:
Dim POS As Worksheet
Dim BRangePOS As Range
Dim LastRow, LastCol As Integer
Dim ColStart, RowStart As Integer
Set POS = ThisWorkbook.Sheets("POS") ' Working sheet
' ------- Where the table starts - to input [xx] -------
Set BRangePOS = POS.[a1] '|
' ------------------------------------------------------
ColStart = BRangePOS.Column ' Column start
RowStart = BRangePOS.Row ' Row Start
LastRow = BRangePOS.CurrentRegion.Rows.Count ' Number of rows
LastCol = BRangePOS.CurrentRegion.Columns.Count ' Number of columns
POS.Range(Cells(LastRow + RowStart - 1, BRangePOS.Column), _
Cells(LastRow + RowStart - 1, LastCol + ColStart - 1)). _
BorderAround Weight:=xlMedium
希望这可以帮助
您可以使用<range>.End()
-这些还可以帮助解决表仅具有一列或一行的情况。 以下代码段选择了从BRangePOS
开始的表的最后一行:
Dim startOfLastRow As Range
Set startOfLastRow = BRangePOS.End(xlDown).End(xlDown).End(xlUp)
With Range(startOfLastRow, startOfLastRow.End(xlToRight).End(xlToRight).End(xlToLeft))
'Insert code to apply border here
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.