Adding Error with Copy & Paste

dan8825

New Member
Joined
Dec 24, 2018
Messages
22
Hello I have the below code, which should show an error msg box and close the two workbooks the macro has already opened when there is nothing to paste.

This is working to well! as in it runs even when there is copied text.

Code:
  Sheets("Tab 2").Select    Range("A1").Select
      ActiveSheet.PasteOn Error GoTo ErrorHandler
ErrorHandler:
    Mainbook.Close Savechanges:=False
    wb1.Close Savechanges:=False
    MsgBox "Nothing to paste!": Err.Clear
    Exit Sub
    Range("A1:F500").Select
    Selection.Style = "Normal"
I need code to run an error message,end sub, close the workbooks it opened when there is noting to paste, otherwise run as normal.

Thanks
 

jmacleary

Well-known Member
Joined
Oct 5, 2015
Messages
829
Office Version
2007
Platform
Windows
If this is your code as typed (i.e. you haven't chopped out any lines from the middle) then your problem is because you have the error code directly after the paste statement, so it will always be run. Insert an Exit Sub (shown in red) so it will be:
Code:
  Sheets("Tab 2").Select    Range("A1").Select
      ActiveSheet.PasteOn Error GoTo ErrorHandler
[COLOR=#ff0000]    Exit Sub[/COLOR]
ErrorHandler:
    Mainbook.Close Savechanges:=False
    wb1.Close Savechanges:=False
    MsgBox "Nothing to paste!": Err.Clear
    Exit Sub
    Range("A1:F500").Select
    Selection.Style = "Normal"
 

dan8825

New Member
Joined
Dec 24, 2018
Messages
22
Hi This is now the full code, the only bit proceeding this is opening the workbooks. This is not working it is pasting 'Activesheet.paste' into a workbook.

The copy would be done manually before hand, as this is in an external programme not another workbook

Code:
    Sheets("Tab 2").Select    Range("A1").Select
   ActiveSheet.Paste
   On Error GoTo ErrorHandler
    Exit Sub


ErrorHandler:
    Mainbook.Close Savechanges:=False
    wb1.Close Savechanges:=False
    MsgBox "Nothing to paste!": Err.Clear
    Exit Sub
    Range("A1:F500").Select
    Selection.Style = "Normal"
Thanks
 

dan8825

New Member
Joined
Dec 24, 2018
Messages
22
If this is your code as typed (i.e. you haven't chopped out any lines from the middle) then your problem is because you have the error code directly after the paste statement, so it will always be run. Insert an Exit Sub (shown in red) so it will be:
Code:
  Sheets("Tab 2").Select    Range("A1").Select
      ActiveSheet.PasteOn Error GoTo ErrorHandler
[COLOR=#ff0000]    Exit Sub[/COLOR]
ErrorHandler:
    Mainbook.Close Savechanges:=False
    wb1.Close Savechanges:=False
    MsgBox "Nothing to paste!": Err.Clear
    Exit Sub
    Range("A1:F500").Select
    Selection.Style = "Normal"
See post above, thanks
 

dan8825

New Member
Joined
Dec 24, 2018
Messages
22

Forum statistics

Threads
1,085,166
Messages
5,382,083
Members
401,768
Latest member
katana_flyer

Some videos you may like

This Week's Hot Topics

Top