Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...