VBA Excel; Rows.Count不计算所有行

时间:2013-05-29 17:44:58

标签: excel-vba vba excel

我正在尝试运行一个脚本,根据单元格的颜色将数字插入到单元格中;如果颜色为红色,则插入#1。电子表格有380行,但脚本在第346行停止运行(插入1)。脚本如下:

Sub InsertOne()

Dim endRow As Long
Dim colorD As Range
Dim Cell As Range


endRow = Sheets(1).Cells(Sheets(1).Rows.Count, "C").End(xlUp).Row

'Ensure ending row is at least Row 2 

If endRow < 2 Then
  endRow = 2
End If

Set colorD = Range("F2", Range("F" & Rows.Count).End(xlUp))

'Loop through each cell in Column D

For Each Cell In colorD

    If Cell.Interior.ColorIndex = 3 Then 

        Cell.Value = 1

    End If

Next Cell

End Sub 

1 个答案:

答案 0 :(得分:3)

尝试以下代码:

计算endRow后,您可以将其用于Set colorD范围。

Sub InsertOne()

    Dim endRow As Long
    Dim colorD As Range
    Dim Cell As Range


    endRow = Sheets(1).Cells(Sheets(1).Rows.Count, "C").End(xlUp).Row

    'Ensure ending row is at least Row 2

    If endRow < 2 Then
        endRow = 2
    End If

    Set colorD = Range("F2:F" & endRow)

    'Loop through each cell in Column D

    For Each Cell In colorD

        If Cell.Interior.ColorIndex = 3 Then

            Cell.Value = 1

        End If

    Next Cell

End Sub