I have been stuck on this for the longest time and it is probably an easy fix I am not seeing. I am trying to select that last row of a table and create a border around it up until the last column. "POS" is the name of the worksheet I am working in. "BRangePOS" is me saying this is where the table begins.
Here is my code.
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
The error I get is a "Method ' Range' of Object_'Worksheet' Failed"
Any help would be great.
Thanks,
G
Maybe you can get some ideas from this. To find the last row:
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
Add function for columns if neeeded
To create a border around the last row of a table :
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
Hope this helps
You can make use of <range>.End()
- these also help cater for the edge cases where your table only has one column or one row. The following code snippet selects the last row of the table starting at 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
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.