[英]Trying to border the last row in VBA
我試圖選擇表格的最后一行,並在整個行周圍使用外邊框,直到最后一列。 這是我的代碼
Cells(Application.Rows.Count, .Columns.Count).End(xlUp).BorderAround Weight:=xlMedium
在我之前
Cells(Application.Rows.Count, 1).End(xlUp).BorderAround Weight:=xlMedium
我的第二行代碼僅與第一個單元格接壤。 我需要它在行中所有單元格的外部邊界。 我已經嘗試過各種不同的操作,例如將其變成“范圍”以僅得到錯誤。 這些是我最接近的嘗試。 我沒有收到錯誤,但沒有執行我需要做的事情。
謝謝,
G
BordersAround
屬性繪制邊框 Option Explicit
Sub BorderAroundBottom()
Dim WS As Worksheet
Dim rFirst As Range, rLast As Range, rTable As Range
'Need to know where table starts
Const ColHdr As String = "ColA"
Set WS = Worksheets("sheet2")
'Find first cell of the table
'Can hardcode this if known
With WS.Cells
Set rFirst = .Find(what:=ColHdr, after:=.Cells(.Rows.Count, 1), _
LookIn:=xlValues, lookat:=xlWhole, searchorder:=xlByRows, _
searchdirection:=xlNext, MatchCase:=False)
If rFirst Is Nothing Then
MsgBox "First Column Header not found"
Exit Sub
End If
Set rLast = .Cells(.Rows.Count, rFirst.Column).End(xlUp)
Set rLast = .Cells(rLast.Row, .Columns.Count).End(xlToLeft)
Set rTable = .Range(rFirst, rLast)
End With
With rTable
.Borders.LineStyle = xlNone
.Rows(.Rows.Count).BorderAround LineStyle:=xlContinuous, Weight:=xlMedium
End With
End Sub
問題在於,在兩次代碼嘗試中,您都只選擇一個單元格。 因為您使用的是Cells
方法,所以您只選擇一個單元格。 您需要將“ Cells
與“ Range
對象結合使用以獲取多單元格區域。
假設您的數據從Sheet1的A1單元格開始,這是工作代碼:
Sub DrawBorder()
Dim rngBottomRowStart As Range
Dim rngBottomRowEnd As Range
Dim rngDataUpperLeftCell As Range
Set rngDataUpperLeftCell = Sheet1.Range("A1")
With rngDataUpperLeftCell
Set rngBottomRowStart = Sheet1.Cells(.End(xlDown).Row, .Column)
Set rngBottomRowEnd = Sheet1.Cells(rngBottomRowStart.Row, .End(xlToRight).Column)
End With
Sheet1.Range(rngBottomRowStart, rngBottomRowEnd).BorderAround Weight:=xlMedium
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.