简体   繁体   中英

Behavior of Cell.Offset versus ActiveCell.Offset in VBA

I have a For loop & a For Each loop in VBA, where I am searching for a string within the content of each cell in the loop using Offset:

Using For Each:

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

Using For:

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

In the bottom example, I must use ActiveCell.Offset. Using Cell.Offset or even Cell.Offset.Value throws an "Object Required" error.

Why is this the case?

In the bottom example you haven't defined what Cell is so VBA has no clue as to what you're trying to do. Cell isn't a special word - it is a variable in the top example

A better way to write your bottom statement would be to use a With instead of the ActiveCell and Select

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

In first loop Cell is a Range object.
In second one Cell is Nothing , you must assign a Range object to it ie:

Set Cell = Range("AK" & i)

Btw, do you declare your variables?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM