繁体   English   中英

剪切-在Excel VBA中粘贴自动检测到的范围

[英]Cut - Paste an auto-detected range in Excel VBA

我正在尝试在定义的位置(特别是紧接在列A或B中最后使用的单元格之后),将具有自动检测的行范围的单元格块剪切并粘贴。

Sub Cut_Range_To_Clipboard()

'Detecting number of used lines in the chunck of code I need to cut
Dim LastRow As Long
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "T").End(xlUp).Row
        MsgBox LastRow
    End With

'Detecting number of used lines in the column I need to paste the code  
Dim LastRow2 As Long
    With ActiveSheet
        LastRow2 = .Cells(.Rows.Count, "B").End(xlUp).Row
        MsgBox LastRow2
    End With

'Cells(20, 3) = T3

Range(Cells(20, 3), Cells(36, LastRow)).Cut
Range(Cells(2, LastRow2 + 1)).Select
ActiveSheet.Paste

Range("T1").Cut
Range(Cells(1, LastRow2 + 1)).Select
ActiveSheet.Paste

Columns("T:AK").EntireColumn.Delete
End Sub

执行代码时,行Range(Cells(2, LastRow2 + 1)).Select输出错误1004,我不明白为什么。

更改您的行:

Range(Cells(2, LastRow2 + 1)).Select

至:

Range("B" & LastRow2 + 1).Select

您需要添加“ Cells的“ Address属性(每次仅使用一个“单元格”参数调用“范围”时都必须添加)。 所以:

Range(Cells(2, LastRow2 + 1).Address).Select

虽然这可以解决您的问题,但是您应该在代码中进行许多更改,包括避免选择,这将提高性能并避免其他问题

暂无
暂无

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

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