excel 复制、插入和删除给定单元格

c0vxltue  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(292)

我在这里要做的是取一个给定的单元格,复制它的值,并在将它的值粘贴到新插入的单元格后删除该单元格。用户输入要删除的单元格和要插入新单元格的单元格。
下面是我的代码:

Sub Test() 
   Dim rngDeleteCell As Range
   Dim rngInsertCell As Range
   
   On Error Resume Next
   Set rngDeleteCell = Application. InputBox( _
          "Select the cell to delete", _
          Type:=8)
   If rngDeleteCell Is Nothing Then Exit Sub
   Set rngInsertCell = Application. InputBox( _
          "Select the cell to insert the new cell upon", _
          Type:=8)
   If rngInsertCell Is Nothing Then Exit Sub 

On Error GoTo 0

With ThisWorkbook.Sheets("Sheet1") 
 .Range(rngInsertCell).Insert xlShiftDown
 .Range(rngDeleteCell).Copy Destination:=Range(rngInsertCell) 
 .Range(rngDeleteCell).Delete Shift:=xlShiftUp
End With
End Sub

但是,当我运行代码时,我收到运行时错误:“1004”:应用程序定义或对象定义的错误。

63lcw9qa

63lcw9qa1#

不确定这是否是您想要的效果,像这样向上移动所有值似乎有点奇怪:

值会向上移动,并有一个空白区域将值保持在原来的位置以下。
您的代码已调整为:

Sub TestInsertDelete()
   Dim rngDeleteCell As Range
   Dim rngInsertCell As Range
   
   On Error Resume Next
   Set rngDeleteCell = Application.InputBox( _
          "Select the cell to delete", _
          Type:=8)
   If rngDeleteCell Is Nothing Then Exit Sub
   Set rngInsertCell = Application.InputBox( _
          "Select the cell to insert the new cell upon", _
          Type:=8)
   If rngInsertCell Is Nothing Then Exit Sub

On Error GoTo 0

 rngInsertCell.Insert xlShiftDown
 rngDeleteCell.Copy Destination:=rngInsertCell
 rngDeleteCell.Delete Shift:=xlShiftUp
End Sub

如果这个奇怪的结果是你想要的,那么好(?),如果不是,请澄清它是如何意味着。如果Ike想要澄清.Range(xx)的功劳,我不介意:)

相关问题