2016-07-22 63 views
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 
     C.Borders(xlEdgeTop).LineStyle = xlNone 

    End If 

Next 
End Sub 

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

enter image description here

+0

你的起始状况如何?据我所知,它不会触及第10行的底部边界。因此,如果首先出现边界,它应该仍然在那里。或者你通过“删除”实际上是否意味着“不添加”? – NiH

+0

在开始的情况下底部边框在那里,但运行上面的代码后,它消失了 –

+0

,你正在使用完全相同的代码和完全相同的设置为您的图片?因为在我的机器上它工作得很好...... @Jordan的答案应该可行,但似乎没有必要。 – NiH

回答

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 

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

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 
相关问题