【问题标题】:Excel VBA On Error Resume Next Returns Value Out Of PositionExcel VBA On Error Resume Next 返回值超出位置
【发布时间】:2016-02-18 15:51:46
【问题描述】:

我正在使用 URL 将图片放在我的工作表中。该代码工作得很好,除了“on error resume next”将前一个单元格的(良好)值放在发生错误的单元格中,而不是它应该的单元格中(一行向上)。然后它继续将值放在它们所属的位置,直到出现另一个错误。

我尝试将“on error resume next”放置在代码的不同区域,但无法解决问题。是错误处理放置在哪里的问题,还是我需要更好的错误处理程序?

谢谢, 安迪

Sub InsertPic()
  On Error Resume Next 
  Dim pic As String 
  Dim myPicture As Picture 
  Dim rng As Range 
  Dim cl As Range 

Set rng = Range("F2:F1131")
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

【问题讨论】:

    标签: vba excel error-handling


    【解决方案1】:

    如果您需要检查 URL 是否存在,那么也许一个辅助函数就足够了?

    Sub InsertPic()
    
      Dim pic As String 
      Dim myPicture As Picture 
      Dim rng As Range 'E3:E1132
      Dim cl As Range 'iterator
    
      Set rng = Range("F2:F1131")
      For Each cl In rng
        pic = cl.Offset(0, -1)
    
        if URLExists(pic) then
          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
        end if
      Next
    
    End Sub
    
    'ref: http://www.mrexcel.com/forum/excel-questions/567315-check-if-url-exists-so-then-return-true.html
    Function URLExists(url As String) As Boolean
        Dim Request As Object
        Dim ff As Integer
        Dim rc As Variant
    
        On Error GoTo EndNow
        Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")
    
        With Request
          .Open "GET", url, False
          .Send
          rc = .StatusText
        End With
        Set Request = Nothing
        If rc = "OK" Then URLExists = True
    
        Exit Function
    EndNow:
    End Function
    

    【讨论】:

    • 有很多丢失的图片,URL 会返回 404 错误,所以我接下来合并了 on error resume,所以它会通过工作表。
    • @AndyAdams 好的-该错误是否发生在特定的代码行上?行Set myPicture =..?
    • 是的,这就是我最初放置错误简历的地方。
    • 查看我的编辑 - 我认为如果它在那里遇到错误,跳过整个迭代块可能是明智的
    • 我得到一个运行时错误。设置 myPicture 时中断...我马上要开会,但非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 2013-01-08
    • 2020-07-30
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多