VBA Offset表现奇怪吗?

时间:2016-11-22 03:57:48

标签: excel vba excel-vba offset

也许还有我不知道的东西,但是我使用Offset在一个单元格中查找值并将它们导出到另一个单元格。有几次,Offset不是我所期望的。例如,在代码中:

Option Explicit

Sub SendToMRP()
Dim AllSales As Worksheet
Dim SendToMRP As Worksheet
Dim ALS  As Range, STM  As Range, AL As Range, Rng As Range

Set AllSales = Worksheets("AllSales")
Set SendToMRP = Worksheets("SendToMRP")

With AllSales
    For Each ALS In Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(3))
        If (ALS.Offset(0, 50) = "Yes") Then
        Else
            'ALS.Offset(0, 50) = "Yes"
            With SendToMRP.Cells(Rows.Count, 1).End(3)
                .Offset(1, 0) = ALS.Offset(0, 0) ' OrderId
                .Offset(1, 1) = ALS.Offset(0, 1) ' StoreFront or    "Amazon"
                .Offset(1, 2) = ALS.Offset(0, 2) ' OrderType'
                .Offset(1, 3) = ALS.Offset(0, 3) ' PurchaseDate'
                .Offset(1, 4) = ALS.Offset(0, 15) ' This should be 4, but 15 is the correct setting
                .Offset(1, 5) = ALS.Offset(0, 5) ' and it continues back at 5

            End With
        End If
    Next
End With

End Sub

Offset的第二个参数有时候并不是我所期望的,我不确定为什么会这样。希望有人可以对此有所了解吗?感谢

1 个答案:

答案 0 :(得分:0)

Excelforum.com上一位非常有帮助的人帮助了我并提供了这个答案。它有效,但我不能说我完全理解为什么。我之前使用过这段代码没有点,它也有效,但这次没有。如果有人可以提供一些指导,我将不胜感激。

With AllSales
For Each ALS In .Range(.Cells(2, 1), .Cells(.Rows.Count, 1).End(3))
    If (ALS.Offset(0, 50) = "Yes") Then
    Else
        'ALS.Offset(0, 50) = "Yes"
        With SendToMRP.Cells(SendToMRP.Rows.Count, 1).End(3)
            .Offset(1, 0) = ALS.Offset(0, 0) ' OrderId
            .Offset(1, 1) = ALS.Offset(0, 1) ' StoreFront or    "Amazon"
            .Offset(1, 2) = ALS.Offset(0, 2) ' OrderType'
            .Offset(1, 3) = ALS.Offset(0, 3) ' PurchaseDate'
            .Offset(1, 4) = ALS.Offset(0, 15) ' This should be 4, but 15 is the correct setting
            .Offset(1, 5) = ALS.Offset(0, 5) ' and it continues back at 5
        End With
    End If
Next
End With