这段代码需要做的事情:
在下面的代码中,
Set Sel = Union(...)
行在 Excel VBA 编辑器中突出显示。Sub Button_Click()
'Declaring variables
Dim Rng As Range, Sel As Range
Dim ws As Sheet2
Dim OldRow As Long, TargetRow As Long
'Selects range on Sheet 2
Set Sel = ws.Range("A" & ActiveCell.Row)
For Each Rng In Selection.Areas
Set Sel = Union(Sel, Intersect(Rng.EntireRow, Range("A:C")))
Next Rng
Sel.Select
'Will try to move selection down
OldRow = 1
TargetRow = 2
ws.Range("A1").Resize(NumRows).Range("B:H").Cut
ws.Range("A" & TargetRow + NumRows).Range("B:H").Insert shift:=xlDown
'Copies selected row to Sheet2
Sel.Copy
ws.[A1].PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End Sub
基于原帖中提供的代码,不需要使用
Cut
操作。意图似乎是copying values
从sheet1到sheet。
使用
.Value
属性赋值比使用 PasteValues
更高效。
微软文档:
Option Explicit
Sub Demo()
Dim oSht1 As Worksheet, oSht2 As Worksheet
Dim srcRng As Range
Const CELL_CNT = 7 ' Col B to H
Set oSht1 = Sheets("Sheet1")
Set oSht2 = Sheets("Sheet2")
oSht1.Activate
Set srcRng = oSht1.Cells(ActiveCell.Row, "B").Resize(1, CELL_CNT)
With oSht2.Range("B2").Resize(1, CELL_CNT)
.Insert xlShiftDown
.Value = srcRng.Value
End With
srcRng.Delete xlShiftUp
End Sub