在使用的单元格范围VBA中应用边框
我正在尝试dynamic地在一组使用的单元格周围应用边框 。 列的范围是(B7:E7) 行数总是会变化的 ,所以代码需要是dynamic的。 我的代码如下没有实现这一点:
Sub Borders() Application.ScreenUpdating = False Dim lngLstCol As Long, lngLstRow As Long lngLstRow = ActiveSheet.UsedRange.Rows.Count lngLstCol = ActiveSheet.UsedRange.Columns.Count For Each rngCell In Range("B7:B" & lngLstRow) If rngCell.Value > "" Then r = rngCell.row c = rngCell.Column Range(Cells(r, c), Cells(r, lngLstCol)).Select With Selection.Borders .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With End If Next Application.ScreenUpdating = True End Sub
这段代码将围绕B7
以外的所有非空单元格放置边界。
Sub Borders() Application.ScreenUpdating = False Dim lngLstCol As Long, lngLstRow As Long lngLstRow = ActiveSheet.UsedRange.Rows.Count lngLstCol = ActiveSheet.UsedRange.Columns.Count For Each rngCell In Range(Range("B7"), Cells(lngLstRow, lngLstCol)) If rngCell.Value > "" Then rngCell.Select 'Select cells With Selection.Borders .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With End If Next Application.ScreenUpdating = True End Sub
下面的代码将使用范围的边界放在B7
:
Sub BordersB() Application.ScreenUpdating = False Dim lngLstCol As Long, lngLstRow As Long lngLstRow = ActiveSheet.UsedRange.Rows.Count lngLstCol = ActiveSheet.UsedRange.Columns.Count With Range(Range("B7"), Cells(lngLstRow, 2)).Borders(xlEdgeLeft) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With With Range(Range("B7"), Cells(7, lngLstCol)).Borders(xlEdgeTop) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With With Range(Cells(7, lngLstCol), Cells(lngLstRow, lngLstCol)).Borders(xlEdgeRight) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With With Range(Cells(lngLstRow, 2), Cells(lngLstRow, lngLstCol)).Borders(xlEdgeBottom) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With Application.ScreenUpdating = True End Sub
这将在列(B:C)的行6下面的所有空白单元格中添加边框,
Sub AddBorders() Dim Rws As Long, Rng As Range, c As Range Rws = Range("A1").SpecialCells(xlCellTypeLastCell).Row Set Rng = Range(Cells(7, "B"), Cells(Rws, "C")) For Each c In Rng.Cells If c <> "" Then With c.Borders .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With End If Next c End Sub