Kris
Kris

Reputation: 21

Very Basic Cut/Paste VBA

Very new to VBA:

I am looking to cut data from cells C2 to the end of the column and paste that data, beginning in cell e2.

I understand this should be extremely simple, but I have tried a few things and am still stuck. The data gets cut directly, but cannot get it to paste.

Recent attempt:

Sub CutPaste_Data()
    
    Range("c2", Range("c2").End(xlDown)).Select
    
    Selection.Cut
    
    Range("e2", Range("e2").End(xlDown)).Select
    
    Selection.PasteSpecial

Upvotes: 0

Views: 2659

Answers (1)

PeterT
PeterT

Reputation: 8557

Since you're new, I'll attempt to coerce some good habits with my example solution :)

Option Explicit

Sub CopyData()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    With ws
        Dim lastRow As Long
        lastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        .Range(.Cells(2, 5), .Cells(lastRow, 5)).Value = .Range(.Cells(2, 3), .Cells(lastRow, 3)).Value
        .Range(.Cells(2, 3), .Cells(lastRow, 3)).Value = vbNullString
    End With
End Sub

Here are the good habits for your VBA code:

  1. Always use Option Explicit
  2. Always be clear on what worksheet or range is being referenced
  3. Use intermediate variables (such as lastRow) to help yourself make your code more readable. Yes, it's a few extra lines of code. But in many instances it can make your code faster (if that's a concern), but you'll find readability will always be a bigger help to you in the long run.
  4. Avoid using Select in your code

Good luck!

Upvotes: 3

Related Questions