使用从一个工作表到另一个工作表的输入框复制范围时出错

时间:2015-08-03 05:28:49

标签: excel excel-vba vba

我一直在尝试通过输入框将定义的范围复制到另一个工作表上的另一个输入框。 我收到错误运行时错误“'1004'应用程序定义或对象定义错误”。在线

          rngCopyFrom.Copy ThisWorkbook.Sheets("Sheet2").Range("rngCopyTo")

我的水平是初学者。请指导我以何种方式改变它以达到预期目标。

 Sub Sample()
  Dim rngCopyFrom As Range
  Dim rngCopyTo As Range
  On Error Resume Next
    Set rngCopyFrom = Application.InputBox("Enter the range from which you  ant to copy", Type:=8)
On Error GoTo 0

On Error Resume Next
     Set rngCopyTo = Application.InputBox("Enter the range from     which   you       want to copy", Type:=8)
On Error GoTo 0

If Not rngCopyFrom Is Nothing Then
    '~~> Copy the range to Shhet2
    rngCopyFrom.Copy ThisWorkbook.Sheets("Sheet2").Range("rngCopyTo")
End If
End Sub

此程序有效如果我定义固定范围,如下面的行所示。

           rngCopyFrom.Copy ThisWorkbook.Sheets("Sheet2").Range("D2:D14")

1 个答案:

答案 0 :(得分:1)

这应该适用于2个输入框:

Option Explicit

Sub copyRangeFromInputBoxes()

    Dim copyFrom As Range, copyTo As Range

    Err.Clear
    On Error Resume Next            'if input is cancelled

    Set copyFrom = Application.InputBox("Select source range", Type:=8)

    If Not copyFrom Is Nothing Then 'if not cancelled

        Set copyTo = Application.InputBox("Select destination range", Type:=8)

        If Not copyTo Is Nothing Then copyFrom.Copy copyTo

    End If

End Sub

代码将从任何工作表中复制并粘贴到任何其他工作表上:

enter image description here