Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

vba runtime error 1004 microsoft excel cannot paste the data

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

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

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...