首页 > 解决方案 > 选择具有 i 个整数的单元格范围

问题描述

我正在尝试选择其中包含 i 个整数的单元格范围。我想要一个特定范围的单元格,而不是选择整行。下面我提供了用于选择整行的代码(它运行良好)以及我为选择特定范围而编写的代码(它不运行)

行代码

With ws2
lastrow1 = .Range("A" & Rows.Count).End(xlUp).Row
For i = 4 To lastrow1
    If .Cells(i, "D").Interior.ColorIndex = -4142 Or .Cells(i, "D").Interior.ColorIndex = 2 Then
        If CopyRange Is Nothing Then
        Set CopyRange = .Rows(i)
        Else
        Set CopyRange = Union(CopyRange, .Rows(i))
        End If
    End If
Next i
End With

范围代码

With ws2
lastrow1 = .Range("A" & Rows.Count).End(xlUp).Row
For i = 4 To lastrow1
    If .Cells(i, "D").Interior.ColorIndex = -4142 Or .Cells(i, "D").Interior.ColorIndex = 2 Then
        If CopyRange Is Nothing Then
        Set CopyRange = .Cells("A & i & ":F" & i)
        Else
        Set CopyRange = Union(CopyRange, .Rows(i))
        End If
    End If
Next i
End With

标签: vbaexcel

解决方案


这里的问题是Cells它只接受像这样的行和列,Cells(row, column)所以你需要使用Range().Range("A" & i & ":F" & i).

您还需要else相应地调整您的部分,因为您仍然Rows(i)Union()

With ws2

    lastrow1 = .Range("A" & Rows.Count).End(xlUp).Row
    For i = 4 To lastrow1
        If .Cells(i, "D").Interior.ColorIndex = -4142 Or .Cells(i, "D").Interior.ColorIndex = 2 Then
            If CopyRange Is Nothing Then
                Set CopyRange = .Range("A" & i & ":F" & i)
            Else
                Set CopyRange = Union(CopyRange, .Range("A" & i & ":F" & i))
            End If
        End If
    Next i

End With

推荐阅读