Excel VBA On Error Resume Next返回值超出位置

时间:2016-02-18 15:51:46

标签: excel vba excel-vba error-handling

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

我尝试在代码的不同区域放置“on next 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

1 个答案:

答案 0 :(得分:0)

如果您需要检查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