首页 文章

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

提问于
浏览
1

我创建了一个代码,用于将图片从链接(该单元格旁边)插入单元格 . 有时,图片会在链接到的文件中删除 . 我得到一个错误400,但当我把'on error resume next'时,它将最后一个单元格中的右侧链接留空,并将该图片放入具有错误链接的单元格中 . 具有右链接的最后一个单元格也是空的 .

'on error resume next'的位置无关紧要(循环之前,或循环中的任何位置)

我怎么能避免这种情况?只是跳过错误的链接并将图片放在正确的位置?

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 回答

  • 1

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

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

    Set 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
    
  • 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
    

    结束子

相关问题