尝试在VBA中选择最后一行和列

时间:2017-09-29 21:38:24

标签: excel vba excel-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

我得到的错误是Object_'Worksheet'失败'的“方法'范围”

任何帮助都会很棒。

谢谢,

4 个答案:

答案 0 :(得分:0)

请尝试以下方法:

Sub test()


Set BRangePOS = POS.Range("A1")

        With POS
            lrowPOS = .Cells(.Rows.Count, 1).End(xlUp).Row
            lcolPOS = .Cells(1, Columns.Count).End(xlToLeft).Column
        End With

    POS.Range(Cells(1, 1), Cells(lrowPOS, lcolPOS)).BorderAround Weight:=xlMedium

End Sub

enter image description here

答案 1 :(得分:0)

也许你可以从中得到一些想法。 要查找最后一行:

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

如果需要,为列添加功能

答案 2 :(得分:0)

要在表格的最后一行周围创建边框:

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

希望这有帮助

答案 3 :(得分:0)

您可以使用<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