试图将最后一行界定在VBA中

我试图select我的表的最后一行,并使用整个行周围的外部边界,直到最后一列。 这是我的代码

Cells(Application.Rows.Count, .Columns.Count).End(xlUp).BorderAround Weight:=xlMedium 

我有之前

 Cells(Application.Rows.Count, 1).End(xlUp).BorderAround Weight:=xlMedium 

我的第二行代码只与第一个单元格相邻。 我需要它到行外的所有单元格的边界。 我已经尝试了不同的东西,如把它变成一个“范围”,只是得到一个错误。 这些是我最亲密的尝试。 我没有得到一个错误,但它没有做我需要做的事情。

谢谢,

G

问题是,在你的两次代码尝试中,你只select一个单元格。 因为您正在使用“ Cells方法,所以只能select一个单元格。 您需要结合Range对象使用Cells来获取多细胞区域。

假设您的数据从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 
  • find表格
  • find最后一行
  • 可以select清除任何现有边界
  • 创build一个范围对象包含最后一行(或任何你想要边框的部分)。
  • 使用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 

在这里输入图像说明