Home > Software engineering >  VBA code for dragging down contents of a cell
VBA code for dragging down contents of a cell

Time:01-10

I wrote a macro to copy and paste (drag down) contents of a cell, the process should repeat itself several times. Yet, I get the "AutoFill Method or Range Class failed" message. What might cause it?

Sub DragDown()

    Range("A10").Select
    Selection.AutoFill Range(Selection.Offset(0, 0), 
    Selection.Offset(2, 0))

    k = 0
    Do Until ActiveCell.Value = "00215F107"
        ActiveCell.Offset(k   7, 0).AutoFill Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(2, 0))
        k = k   7
    Loop

End Sub

CodePudding user response:

Does changing this

ActiveCell.Offset(k   7, 0).AutoFill Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(2, 0))
  

to this

Selection.AutoFill Range(Selection.Offset(0, 0), Selection.Offset(k   7, 0))

solve your problem?

CodePudding user response:

It can't work becuase destination of your Autofill must include the source range. In your case - destination: Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(2, 0)) does not include source ActiveCell.Offset(k 7, 0).

You can use .Copy and .Paste commands. For example:

    Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(2, 0)).Copy
    ActiveCell.Offset(k   7, 0).Paste

But if you want to copy tha same content multiple times, you can put your Copy command before your Do-Until loop.

  • Related