Excel VBA:单循环+ If-Statement; 运行时错误1004

我想遍历一列,并将该范围内的所有单元格与单元格“AD2”的值x进行比较。 如果单元格i的值小于值x,我希望单元格i被标记为红色。 在运行以下代码时:

Sub Button10() Dim i As Long Dim x As Integer x = Range("AD2").Value If Cells(i, 26).Value < x Then Cells(i, 26).Font.Color = vbRed For i = 1 To 500 Next i End If End Sub 

我得到以下错误:

运行时错误“1004”:对象'Range'的方法'_Default'失败。

现在我已经缩进了你的代码,希望你能看到你的逻辑在你的For循环之外。

你得到一个错误,因为当你声明i As Long它被初始化的值为0 。 因此,这条线会失败,因为i = 0是不会返回一个有效的范围:

 If Cells(i, 26).Value < x Then 

所以试试这个:

 Sub Button10() Dim i As Long Dim x As Integer x = Range("AD2").Value For i = 1 To 500 If Cells(i, 26).Value < x Then Cells(i, 26).Font.Color = vbRed End If Next i End Sub