在已使用的单元格范围VBA中应用边框

时间:2015-04-25 07:16:33

标签: excel vba loops excel-vba border

我正在尝试动态地应用围绕一组使用过的单元格的边框列范围为(B7:E7) 的数量始终变化,因此代码必须是动态的。我的下面的代码没有达到这个目的:

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

2 个答案:

答案 0 :(得分:3)

此代码将所有非空单元格的边框置于utcDate.ToLocalTime(); 之外。

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

答案 1 :(得分:1)

这将为列(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