简体   繁体   中英

VBA ActiveCell.Offset unexpected results - skipping cells

I'm getting unexpected results with the code snippet below in a worksheet module.

It correctly does the "Label 5" and "Qty" cells but "Description" is placed in cell L22 instead of B22

I did a debug.print on the line numbers at each stage and they are incrementing. A21 is a merged cell. L22 is also outside the print area of the worksheet if that matters any.

If I uncomment the ActiveCell.Offset(lineNumber, 0).Select it selects the correct cell of A22 but then puts the Qty and Description into cells A23 and B23 which in the proper columns but wrong row.

Sub test()
On Error Resume Next

Dim lineNumber As Integer

lineNumber = 0

    Worksheets(1).range("A21").Select
     ActiveCell.Offset(lineNumber, 0).value = "Label 5"   'A21
     lineNumber = lineNumber + 1
     ActiveCell.Offset(lineNumber, 0).value = "Qty" 'A22
     ActiveCell.Offset(lineNumber, 1).value = "Description" 'B22 -- Prints to L22
     lineNumber = lineNumber + 1

End Sub

offsetissue

This is why you shouldn't use Active* , Select , and Offset . Use hard object references, {null}, and Cells or Range respectively. You're writing a fixed layout, so just hard code it:

Sub test()
    With Worksheets(1)
        .Range("A21").Value = "Label 5"  `On merged ranges, just use the top left cell.
        .Range("A22").Value = "Qty"
        .Range("B22").Value = "Description"
    End With
End Sub

If you need to reuse this, you can pass it a row parameter for where the merged "header" cell is located:

Private Sub WriteHeaders(targetSheet As Worksheet, titleRow As Long, heading As String)
    With targetSheet
        .Cells(titleRow, 1).Value = heading
        .Cells(titleRow + 1, 1).Value = "Qty"
        .Cells(titleRow + 1, 2).Value = "Description"
    End With
End Sub

Then you can call it like this:

WriteHeaders Worksheets(1), 21, "Label 5"

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