如果单元格不是空的,请添加顶部边框
这是添加顶部边框。
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
但是,在最后一行中,下边框被删除。 如何修改循环?
您可以检查'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
或者,你可以用ActiveSheet.Cells(Rows.Count, "B").End(xlup).Row
这样的东西代替10, ActiveSheet.Cells(Rows.Count, "B").End(xlup).Row
如果你不知道范围的结束位置,但是想select列中最后一个非空的单元格B.
你也可以试试这个
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