在错误恢复时,插入图片时会出现错误的结果

时间:2015-03-24 09:54:16

标签: vba excel-vba excel

我创建了一个代码,用于将图片从链接(该单元格旁边)插入单元格。有时,图片会在链接到的文件中删除。我收到错误400,但是当我在接下来的错误恢复时出现错误#39;它将最后一个单元格中的右侧链接留空,并将该图片放入具有错误链接的单元格中。具有右链接的最后一个单元格也是空的。

&#39>关于错误恢复的位置'无关紧要(循环之前,或循环中的任何地方)

我该如何避免?只是跳过错误的链接并将图片放在正确的位置?

Sub InsertPictures()

    Call DeleteAllPicturesInRange

    Dim pic As String
    Dim myPicture As Picture
    Dim rng As Range
    Dim cl As Range

    Set rng = Range("J5:J124")

    For Each cl In rng

        pic = cl.Offset(0, 1)

        Set myPicture = ActiveSheet.Pictures.Insert(pic)

        With myPicture
            .ShapeRange.LockAspectRatio = msoFalse
            .Width = cl.Width
            .Height = cl.Height
            .Top = Rows(cl.Row).Top
            .Left = Columns(cl.Column).Left
        End With

    Next

End Sub

2 个答案:

答案 0 :(得分:1)

添加一行代码会清空变量,并确保您不会跨循环使用变量。基本上你有两个变量,你冒着在下一个循环中默认使用的风险,如果你使用下一个错误恢复,它们是picmypicture一个好的做法就是尽快清除这些变量你完成了它们,因为它们默认在下一个循环中使用,因为没有设置新值。这有意义吗?

注意 - 要清除范围变量,必须将其分配给另一个范围,因此Cell(1,1)将其设置为符合您需要的任何其他单元格

设置myPicture = Nothing

pic = Cell(1,1)

Sub InsertPictures()

Call DeleteAllPicturesInRange

Dim pic As String
Dim myPicture As Picture
Dim rng As Range
Dim cl As Range

Set rng = Range("J5:J124")

    For Each cl In rng

    pic = cl.Offset(0, 1)

    Set myPicture = ActiveSheet.Pictures.Insert(pic)

    With myPicture
        .ShapeRange.LockAspectRatio = msoFalse
        .Width = cl.Width
        .Height = cl.Height
        .Top = Rows(cl.Row).Top
        .Left = Columns(cl.Column).Left
    End With

    Set myPicture = Nothing
    pic = cell(1,1)
Next

End Sub

答案 1 :(得分:0)

感谢您的帮助。我将on error resume nextSet mypicture = Nothing结合使用,并且有效!

Sub InsertPictures()

Call DeleteAllPictures

Dim Pic As String 'file path of pic
Dim myPicture As Picture 'embedded pic
Dim rng As Range 'range over which we will iterate
Dim cl As Range 'iterator

Set rng = Range("J5:J124")
For Each cl In rng

Pic = cl.Offset(0, 1)

    On Error Resume Next

    Set myPicture = ActiveSheet.Pictures.Insert(Pic)

    With myPicture
        .ShapeRange.LockAspectRatio = msoFalse
        .Width = cl.Width
        .Height = cl.Height
        .Top = Rows(cl.Row).Top
        .Left = Columns(cl.Column).Left
    End With

Set myPicture = Nothing

Next

End Sub