剪切+插入有时会删除和移动单元格,有时则不会。为什么?

时间:2014-11-23 09:36:09

标签: vba excel-vba excel

我有以下用于剪切和粘贴行的代码:

'Cut range from source row
Dim lSourceRow As Long
Dim lSourceStartColumn As Long
Dim lSourceEndColumn As Long
lSourceRow = t.Row
lSourceStartColumn = loSource.Range.Column
lSourceEndColumn = loSource.Range.Column + loSource.ListColumns.Count - 1
wksSource.Range(wksSource.Cells(lSourceRow, lSourceStartColumn), wksSource.Cells(lSourceRow, lSourceEndColumn)).Cut

'Select target worksheet for insert method
wksTarget.Activate

'Insert range into target row
Dim lTargetRow As Long
Dim lTargetStartColumn As Long
Dim lTargetEndColumn As Long
lTargetRow = loTarget.DataBodyRange.Row + loTarget.ListRows.Count
lTargetStartColumn = loTarget.Range.Column
lTargetEndColumn = loTarget.Range.Column + loTarget.ListColumns.Count - 1
wksTarget.Range(Cells(lTargetRow, lTargetStartColumn), Cells(lTargetRow, lTargetEndColumn)).Insert

'Strange thing that original row is deleted if source and target are on the same sheet, otherwisw not
If Not wksSource Is wksTarget Then
    wksSource.Range(wksSource.Cells(lSourceRow, lSourceStartColumn), wksSource.Cells(lSourceRow, lSourceEndColumn)).Delete
End If

当我在同一张纸上剪切和粘贴时,剪切的细胞被删除,它们下面的细胞向上移动。

当我剪切并粘贴到另一张纸时,切割的单元格不会被删除,而是留空。

这对我来说似乎不一致。在这两种情况下,我能做些什么来让VBA删除切割的单元格并将单元格移位?

1 个答案:

答案 0 :(得分:1)

不幸的是,Excel本身并没有这样做,因此您当前手动删除它的方法是实现您所需要的必要步骤。

作为建议,您可以尝试将Range变量设置为您正在移动的区域(剪切/粘贴),这将阻止您复制选择逻辑。这可能会使代码更具可读性,并使解决方案更加可口:

Dim moveCells As Range
Set moveCells = wksSource.Range(wksSource.Cells(lSourceRow, lSourceStartColumn), wksSource.Cells(lSourceRow, lSourceEndColumn))
moveCells.Cut

[...] ' All other code remains unchanged.

If Not wksSource Is wksTarget Then
    ' Excel doesn't shift the cut cells when pasting to an alternate sheet.
    ' Must manually do this.
    moveCells.Delete
End If