如果单元格不为空,请添加“顶部”边框

时间:2016-07-22 08:15:28

标签: excel vba excel-vba

这是添加顶部边框。

Sub getBorders()
Dim rngToChange As Range
Dim C As Range
Set rngToChange = ActiveSheet.Range("B6:C10")

For Each C In rngToChange
    If C <> "" Then
        C.Borders(xlEdgeTop).LineStyle = (xlContinuous)
        C.Borders.Weight = xlThin
        C.Borders.ColorIndex = xlAutomatic
    Else
        C.Borders(xlEdgeTop).LineStyle = xlNone

    End If

Next
End Sub

但是,在最后一行中,底部边框将被删除。如何修改循环?

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以检查“C”是否在最后一行,然后在满足条件时应用底部边框:

Sub getBorders()
Dim rngToChange As Range
Dim C As Range
Set rngToChange = ActiveSheet.Range("B6:C10")

For Each C In rngToChange
    If C <> "" Then
        C.Borders(xlEdgeTop).LineStyle = (xlContinuous)
        C.Borders.Weight = xlThin
        C.Borders.ColorIndex = xlAutomatic
    Else
        C.Borders(xlEdgeTop).LineStyle = xlNone
    End If
    'If you always know the end of your range simply replace 10 with the end row
    If C.Row = 10 Then  
        C.Borders(xlEdgeBottom).LineStyle = (xlContinuous)
        C.Borders.Weight = xlThin
        C.Borders.ColorIndex = xlAutomatic
    End if
Next
End Sub

或者,如果您不知道范围的结束位置但想要选择B列中的最后一个非空单元格,则可以用ActiveSheet.Cells(Rows.Count, "B").End(xlup).Row替换10。

答案 1 :(得分:0)

你也可以尝试这个

  Sub getBorders()
     Dim rngToChange As Range
     Dim C As Range
     Set rngToChange = ActiveSheet.Range("B6:C10")

    For Each C In rngToChange
       If C <> "" Then
        C.Borders(xlEdgeTop).LineStyle = (xlContinuous)
        C.Borders.Weight = xlThin
        C.Borders.ColorIndex = xlAutomatic
      Else
     If C = "B10" Or C = "C10" Then
       Else
        C.Borders(xlEdgeLeft).LineStyle = (xlContinuous)
        C.Borders(xlEdgeRight).LineStyle = (xlContinuous)
        C.Borders(xlEdgeTop).LineStyle = xlNone
     End If
End If

 Next
 End Sub