【问题标题】:on error resume next gives wrong result when inserting pictureson error resume next 在插入图片时给出错误的结果
【发布时间】:2015-03-24 09:54:16
【问题描述】:

我创建了一个代码,用于将图片从链接(在该单元格旁边)插入到单元格中。有时,图片链接到的文件中的图片会被删除。我收到一个错误 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

【问题讨论】:

  • 这里的教训:除非你知道错误是什么,否则不要使用On Error Resume Next

标签: vba excel


【解决方案1】:

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

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

设置 myPicture = 无

pic = 单元格(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

【讨论】:

    【解决方案2】:

    感谢您的帮助。我添加了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
    

    结束子

    【讨论】:

      猜你喜欢
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多