0
votes

I have some code in VBA, I have several Country and Product buttons.

My goal is when I click a button, Cells (1, 1) will be overwrite with a text like "US", "CA", "MX" and cells (2, 1) with "PC", "Printers"

Example: If Cells (1, 1) = US Then select a Range, copy the Range and finally paste it in the same sheet but as a picture and in a different Range.

But firts I need to delete the previous picture to replace it with the new one.

It works, but sometimes it appears a message with the following error and doesn't paste the range.

'runtime error 1004 - microsoft excel cannot paste the data'

The code to delete pictures.

Sub Delete_Pictures()
    For Each Shape In ActiveSheet.Shapes
        If Left(Shape.Name, 7) = "Picture" Then
           Shape.Delete
        End If
    Next
End Sub

Let's suppose I already click on PC Button and Cells (2, 1) contains = 'PC'

If I click US Button the macro should do the following.

Sub Button_US()
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Cells(1, 1) = "US"

    Call Delete_Pictures

       If Cells(2, 1) = "PC" Then
       Range("BP73:BX87").Select
       Selection.Copy
           With Worksheets("Main")
               .Activate
               .Range("Z7").Select
               .Pictures.Paste(Link:=True).Select
           End With
       End If

   Application.CutCopyMode = False

   Application.ScreenUpdating = True
   Application.EnableEvents = True

 End Sub

I want to know if there is a way to correct this one, or if there are other ways to copy and paste a range without this kind of errors.

1
what is that Call Delete_Pictures for? Isn't it removing all pictures from the same worksheet whose Range("BP73:BX87") you're hoping to copy pictures from?user3598756

1 Answers

5
votes

I'm betting it's the .Select. See this thread on how to avoid using .Select, which can cause issues.

Sub Button_US()
Dim myPic As Picture
Application.ScreenUpdating = False
Application.EnableEvents = False

Cells(1, 1) = "US"

'Call Delete_Pictures

If Cells(2, 1) = "PC" Then
    Range("BP73:BX87").Copy
    With Worksheets("Main")
        Set myPic = .Pictures.Paste(Link:=True)
        myPic.Left = .Range("Z7").Left
        myPic.Top = .Range("Z7").Top
'        .Range("Z7").Pictures.Paste(Link:=True).Select
    End With
End If

Application.CutCopyMode = False

Application.ScreenUpdating = True
Application.EnableEvents = True

End Sub

(Also, I got some insight from this thread)