VBA中Cell.Offset与ActiveCell.Offset的行为

我有一个For循环和VBA中的For Each循环,在这里我使用Offset在循环中的每个单元格的内容中search一个string:

为每个使用:

Lastrow = ActiveSheet.Range("A2").End(xlDown).Row Set Myrange = ActiveSheet.Range("M2:M" & Lastrow) countrows = Cells(Cells.Rows.Count, "A").End(xlUp).Row For Each Cell In Myrange If strPattern <> "" Then If Cell.Offset(0, 31) <> "Fizz" Then strInput = Cell.Value 

用于:

 countrows = Cells(Cells.Rows.Count, "A").End(xlUp).Row For i = 1 To countrows Range("AK" & i).Select check_value = ActiveCell If ActiveCell.Offset(0, 7) <> "Buzz" Then ActiveCell.EntireRow.Copy 

在底部的例子中,我必须使用ActiveCell.Offset。 使用Cell.Offset甚至Cell.Offset.Value将抛出一个“Object Required”错误。

这是为什么?

在底部的例子中,你还没有定义Cell是什么,所以VBA不知道你在做什么。 Cell不是一个特殊的单词 – 它是顶部示例中的一个variables

编写底部语句的更好方法是使用With而不是ActiveCellSelect

 countrows = Cells(Cells.Rows.Count, "A").End(xlUp).Row For i = 1 To countrows With Range("AK" & i) check_value = .Value2 If .Offset(0, 7) <> "Buzz" Then .EntireRow.Copy End If End With Next i 

在第一个循环中,Cell是一个Range对象。
在第二个单元格是Nothing ,你必须指定一个Range对象,即:

 Set Cell = Range("AK" & i) 

顺便说一句,你是否声明你的variables?