Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert user defined range into another worksheet

Tags:

excel

vba

I set a range and can show it with msg box and rng.address but i can't manage to copy/insert or do aynthing with i. In my code snippet i try to copy it but later on i always need to insert the range after the first column in the other sheet.

Here's one particular problem. I am sure it's very easy or i just misunderstand things.I also don't understand

Dim rng As Range


Set rng = Application.InputBox("Please choose a range", "Obtain Range Object", Type:=8)

 If MsgBox("Your choice " & rng.Address & " ?", vbYesNo, "Confirm") = vbYes Then
    GoTo continue:
    Else
    GoTo retry:
    End If

continue:


Worksheets("Sheet source").Range(rng).Copy Worksheets("sheet destination").Range("A1").Paste
like image 625
Matthias94 Avatar asked Dec 10 '25 15:12

Matthias94


1 Answers

You declared Dim rng As Range so is already a range in a specific sheet therefore Range(rng) doesn't work, because Range() awaits an address as parameter (not a range).

Also if you use the .Copy syntax in one line (with destination as parameter) you don't need to .Paste.

It should be

rng.Copy Worksheets("sheet destination").Range("A1")

Also using Goto (outside an error handing) is a very bad practice. Instead use something like that:

Sub AskMe()
    Dim Rng As Range

    Do
        On Error Resume Next 'next line throws error if user presses cancel so we hide **all** error messages now (and turn them on later!)
        Set Rng = Application.InputBox("Please choose a range", "Obtain Range Object", Type:=8)
        If Err.Number <> 0 Then Exit Sub 'if an error occurred then the user pressed cancel (so we exit)
        On Error GoTo 0 'always re-activate error reporting! Otherwise all error messages stay hidden.
    Loop Until MsgBox("Your choice " & Rng.Address & " ?", vbYesNo, "Confirm") = vbYes
    'repeat asking for a range until yes is pressed

    Rng.Copy Worksheets("sheet destination").Range("A1")
End Sub
like image 96
Pᴇʜ Avatar answered Dec 13 '25 09:12

Pᴇʜ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!