剪切 – 在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,我不明白为什么。

您需要添加CellsAddress属性(无论何时调用只有一个单元格参数的范围,必要的)。 所以:

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

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

改变你的路线:

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

至:

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