2016-07-22 293 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 
相關問題