简体   繁体   English

非常基本的剪切/粘贴 VBA

[英]Very Basic Cut/Paste VBA

Very new to VBA: VBA 非常新:

I am looking to cut data from cells C2 to the end of the column and paste that data, beginning in cell e2.我希望将单元格 C2 中的数据剪切到列的末尾并粘贴该数据,从单元格 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

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:以下是您的 VBA 代码的好习惯:

  1. Always use Option Explicit 始终使用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.使用中间变量(例如lastRow )来帮助自己使代码更具可读性。 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避免在代码中使用Select

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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