VBA如何仅为可见单元格每隔5行创建单元格底部边框

时间:2016-10-28 19:06:26

标签: excel vba excel-vba loops

我希望将每个第5个可见行应用一个底部边框。

循环从第14行开始并继续到第200行。

我想让循环在单元格中查找值(i,“D”)。即列D中的每个 ith 行。

目前我在设置x = 0的行上遇到Object Required错误。我对此感到困惑,因为我在顶部声明x为整数。

Sub Border()

Dim i As Integer
Dim x As Integer
Dim sumsht As Worksheet
Set sumsht = ThisWorkbook.Sheets("Sheet1")

x = 0

  For i = 14 To 200
    x = sumsht.Cells(i, "D") + x
        If x = 5 Then
            With Worksheets("Sheet1").Rows(i).Borders(xlEdgeBottom)
                .LineStyle = xlContinuous
                .Weight = xlThin
                .ColorIndex = 1
            End With
        Else
        End If  
  Next i

End Sub

1 个答案:

答案 0 :(得分:2)

试试这个。您需要考虑行的高度。

正如其他人所说,set与范围一起使用,而不仅仅是变量(如x)。您也可以使用sumsht,但不要在任何地方定义它。

Option Explicit
Sub add_lines()
Dim rw, ct As Integer


ct = 0

For rw = 14 To 200
    If Rows(rw).Height <> 0 Then
        ct = ct + 1
    End If
    If ct = 5 Then
        With Worksheets("Sheet1").Rows(rw).Borders(xlEdgeBottom)
                .LineStyle = xlContinuous
                .Weight = xlThin
                .ColorIndex = 1
            End With
        ct = 0
    End If
Next rw

End Sub

删除其他边框使用此功能(感谢@Comintern):

Range("A1:D22").Borders.LineStyle = xlLineStyleNone