VBA边框Excel依赖页面大小

我想根据页面的大小在我的每个Excel页面周围创build边框,例如行数和列数可以随时变化。 我试过这个,但它是特定的单元格

Sub AddBorders() With Range("B8:I10") .Borders(xlEdgeLeft).LineStyle = xlContinuous .Borders(xlEdgeRight).LineStyle = xlContinuous .Borders(xlEdgeBottom).LineStyle = xlContinuous .Borders(xlEdgeTop).LineStyle = xlContinuous End With End Sub 

UsedRange 永远不能用于find有数据的最后一个单元格。 这是非常不可靠的。 。 你可能想看到这个用于解释usedrange

总是find最后一行和最后一列,然后创build范围。 看到这个例子。

我会推荐这种方式

 Sub AddBorders() Dim ws As Worksheet Dim lastrow As Long, lastcol As Long Set ws = Sheet1 '<~~ Change as applicable With ws '~~> Check if sheet has any data If Application.WorksheetFunction.CountA(.Cells) <> 0 Then '~~> Get Last Row lastrow = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row '~~> Get Last Column lastcol = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column '~~> Work with the range .Range(.Cells(1, 1), .Cells(lastrow, lastcol)).BorderAround _ xlContinuous, xlMedium End If End With End Sub 

跟随评论

这效果更好。 唯一的问题是边界不会绕过任何图表/图表。 有没有办法做到这一点? 感谢您的帮助 – user1296762 7分钟前

也抱歉,我们可以有底部边界最后一行+ 1作为一些行分组,因此行不能被看到如果不扩大 – user1296762 5分钟前

这是你正在尝试?

 Sub AddBorders() Dim ws As Worksheet Dim lastrow As Long, lastcol As Long Dim shp As Shape Set ws = Sheet1 '<~~ Change as applicable With ws '~~> Check if sheet has any data If Application.WorksheetFunction.CountA(.Cells) <> 0 Then '~~> Get Last Row lastrow = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row '~~> Get Last Column lastcol = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column End If '~~> Loop through shapes and find the last row and column For Each shp In .Shapes If shp.BottomRightCell.Row > lastrow Then lastrow = shp.BottomRightCell.Row If shp.BottomRightCell.Column > lastcol Then lastcol = shp.BottomRightCell.Column Next If lastrow <> 0 And lastcol <> 0 Then 'Also sorry can we have the bottom border last row+1 as some rows are 'grouped up and therefore line can't be seen if not expanded '– user1296762 2 mins ago lastrow = lastrow + 1: lastcol = lastcol + 1 '~~> Work with the range .Range(.Cells(1, 1), .Cells(lastrow, lastcol)).BorderAround _ xlContinuous, xlMedium End If End With End Sub 

Sceenshot

在这里输入图像说明

您可以使用:

 ActiveSheet.UsedRange.BorderAround xlContinuous, xlMedium 

我相信这会做到。