[英]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.