Vba ошибка 404

So, I have this spreadsheet with a list of about 5000 URLs. (All pages on our corporate intranet.)

We know some of the links are broken, but don’t know of a good way to determine which without clicking all 5000 links.

Normally this would be a simple matter: Create a web page with links to the 5000 pages, and then check the links with a tool like Xenu Link Sleuth.

But that won’t work in this case because many of the links are being redirected, and the redirect code spoofs HTTP.response 200, which tricks Xenu into treating it as a valid URL.

However, there is some good news: The redirect script does not run from within Excel. If you click a bad link inside Excel, the redirect script does not execute and the HTTP response is reported back to Excel. I believe Excel should be able to identify the correct HTTP response code (404) — or at least whether the link was valid or not.

Which brings me to my question:

Is there a way using VBA to write a script that would click through every link and capture the result? The result captured could be in the form of the HTTP response code or anything else you think would be useful in finding the bad links in this list of 5000 pages. Ideally the result would be written to a cell in the spreadsheet adjacent to the link.

If anyone if familiar enough with VBA to suggest a solution to this problem, I would be eternally grateful!

  • Remove From My Forums
  • Question

  • I’m running VBA in Access to export data to a saved macro enabled Excel file.  After Access exports data to the Excel file, the user is prompted to run an Excel based report.  When the user clicks to do so, the report is generated, and the original
    macro enabled Excel file is closed, preventing the user from saving over it, or making any changes to the VBA.  Functionally, everything that I want to happen is happening, except an error on the following line in Access:

    ApXL.Run "CallReport3.XLSM!GenReports2"

    This line calls in Excel:

     Sub GenReports2()
    
    
    Dim rptType As Integer
    Dim wrkBK As Workbook
    Set wrkBK = ActiveWorkbook
    
    
    rptType = MsgBox("For Client Report Click Yes, For Complete Report Click No", vbYesNo)
    'MsgBox (rptType)
    
    If rptType = 6 Then
    
    'Call callreport
    Application.Run "callreport2"
    
    
    Application.CutCopyMode = False
    
    wrkBK.Close False
    
    ElseIf rptType = 7 Then
    Worksheets("Report").Activate
    End If
    
    
    
    
    
    
    
    
    'MsgBox "Hi, thanks for opening me", vbInformation, "Ozgrid.com"
    
    
    
    End Sub
    

Answers

  • I’ve found the solution, will try to post it shortly.

    • Marked as answer by

      Thursday, May 3, 2012 2:38 AM

How To Check Bulk 404 Status in Excel - VBA Code
How To Check Bulk 404 Status in Excel — VBA Code

Easily and quickly check server header status codes, response headers, and redirect chains in real time with this excel VBA code. This simple VBA code is helpful if you have a huge number of URL list. Some common server HTTP status codes:

  • HTTP 200 OK / Success, the request has Succeeded and the server has responded with a standard response.
  • HTTP 301 Redirect, the requested URL has been Permanently Moved to a new location / URL. This redirect transfers visitors and link value to the new destination URL.
  • HTTP 302 Found, the requested URL has been Temporarily Moved to a new location / URL. This redirect transfers visitors to the new destination URL. The link value isn’t transferred to the new URL.
  • HTTP 404 Not found, the requested URL has not been found. In this case, you should probably check the URL you submitted or use a 301 permanent redirect to transfer visitors and link value to right URL.
  • Other, there’s probably a problem you like to fix!

The excel VBA function will display each set of HTTP 404 Headers in the specified column. There is no restriction in using in bulk checking HTTP header status. Just copy-paste the entire code in your excel VBA window. And, you are done.

Excel VBA Code for Checking Bulk HTTP 404 Status

Public Function ServerResponse(url As String) As Integer
On Error Resume Next
With CreateObject(«WinHttp.WinHttpRequest.5.1»)
.Open «GET», url
.Send
ServerResponse = .Status
End With
End Function

Instructions to Run the VBA Macro Code to Check Bulk 404 Status in Excel


Please follow the below steps to execute the VBA code to check bulk 404 status in Excel.

Step 1: Open your Keyword research report
Step 2: Press Alt+F11 – This will open the VBA Editor
Step 3: Insert a code module from then insert menu
Step 4: Copy the above code and paste in the code module which have inserted in the above step
Step 5: Enter some data in first column of worksheet. Also enter some duplicate data for testing purpose
Step 6: Now press F5 to execute the code

Данная функция позволяет проверить, доступен ли тот или иной веб-ресурс с вашего компьютера, и получить код состояния HTTP

Как известно, при переходе по ссылке (URL), веб-сервер возвращает код состояния HTTP.

Наиболее популярный коды ответа веб-сервера: (перечень всех кодов состояния можно посмотреть в Википедии)

  • 200 OK («хорошо»)
  • 403 Forbidden («запрещено»)
  • 404 Not Found («не найдено»)

Код состояния — это целое число из 3 цифр.
По первой цифре можно определить, доступен ли ресурс: если первая цифра 2, то ресурс доступен, если любая другая — то скорее всего нет.

Пример макроса, проверяющего доступ к различным ресурсам по URL:

Sub ПроверкаURL()
    URL$ = "http://excelvba.ru/resources/FillDocuments"    ' ссылка на каталог
    MsgBox GetURLstatus(URL$), vbInformation, URL$    ' возвращает 200 (папка существует, доступ открыт)

    URL$ = "http://ExcelVBA.ru/updates/"    ' ссылка на каталог
    MsgBox GetURLstatus(URL$), vbInformation, URL$    ' возвращает 403 (папка существует, но доступ к ней закрыт)

    URL$ = "http://ExcelVBA.ru/mail.jpg"    ' ссылка на файл
    MsgBox GetURLstatus(URL$), vbInformation, URL$    ' возвращает 200 (файл существует, доступен)

    URL$ = "http://excelvba.ru/code/GetURLstatus"    ' ссылка на веб-страницу
    MsgBox GetURLstatus(URL$), vbInformation, URL$    ' возвращает 200 (веб-страница существует, доступна)

    URL$ = "http://excelvba.ru/error-test-macro"    ' ссылка на веб-страницу
    MsgBox GetURLstatus(URL$), vbInformation, URL$    ' возвращает 404 (веб-страница по такой ссылке не найдена)

    URL$ = "http://excelvba.ru/.htaccess"    ' ссылка на недоступный файл
    MsgBox GetURLstatus(URL$), vbInformation, URL$    ' возвращает 403 (файл существует, не доступен)

    URL$ = "excelvba.ru"    ' неверная ссылка - без «http://»
    MsgBox GetURLstatus(URL$), vbInformation, URL$    ' возвращает 0 (URL в неверном формате - запрос не выполнен)
End Sub

Код функции GetURLstatus, позволяющий выполнять такую проверку веб-ресурсов:

Function GetURLstatus(ByVal URL$) As Long
    ' функция проверяет наличие доступа к ресурсу URL$ (файлу или каталогу)
    ' возвращает код ответа сервера (число), либо 0, если ссылка ошибочная
    ' (200 - ресурес доступен, 404 - не найден, 403 - нет доступа, и т.д.)
    On Error Resume Next: URL$ = Replace(URL$, "", "/")
    Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
    xmlhttp.Open "GET", URL, "False"
    xmlhttp.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
    xmlhttp.send
    GetURLstatus = Val(xmlhttp.Status)
    Set xmlhttp = Nothing
End Function

Доброе время суток
У объекта Worksheet есть коллекция Hyperlinks, у каждого члена коллекции есть свойство Address.
Проверяете, что начало или http:// или https:// , если без полного определения, то положим все ссылки ведут в Web <_<
И такой функцией проверяете, что вернёт
[vba]

Код

Public Function testUrl(ByVal thisUrl As String) As Long
    Dim pHttp As Object
    Set pHttp = CreateObject(«Msxml2.XMLHTTP»)
    pHttp.Open «GET», thisUrl
    pHttp.send
    Do Until pHttp.readyState = 4
        ‘можно вписать проверку на выход за временные рамки
        DoEvents
    Loop
    testUrl = pHttp.Status
End Function

[/vba]
Для примера
[vba]

Код

Public Sub test()
    Debug.Print testUrl(«http://www.excelworld.ru/forum/10-38166-100»)
    Debug.Print testUrl(«http://www.excelworld.ru/forum/10-38166-1»)
End Sub

[/vba]
Успехов.

Понравилась статья? Поделить с друзьями:
  • Vba ошибка 3705
  • Vba ошибка 361
  • Vba ошибка 3021
  • Vba ошибка 3001
  • Vba ошибка 2501