Ошибка автоматизации ввода данных сайта, так как сайт все еще загружается - PullRequest
1 голос
/ 24 марта 2019

У меня есть код, который выбирает данные из нескольких столбцов из ThisWorkbook и помещает различные поля на веб-сайт в Internet Explorer.Сайт загружается после нажатия на line1 (кнопка поиска).Затем код выдает ошибку в line2 , где он нажимает на флажок, поскольку флажок еще не установлен, если веб-сайт все еще загружается.(Я думаю, что веб-сайт построен на Sharepoint и плохо закодирован.)

Есть ли какой-либо код, который повторяет строку 2 через 2-3 секунды и продолжается дальше всякий раз, когда появляется ошибка?Я попытался обработчик ошибок повторить код, но не сработал.

    Sub CSA_Upload()

        Dim test1 As Long, test2 As Long
        test1 = Timer

        Dim n As Long
        Range("A1").Select
        n = Selection.End(xlDown).Row
        ThisWorkbook.Sheets("Data").Range("A2:A" & n).Interior.ColorIndex = 0

        Dim IE As Object
        Dim doc As Object
        Dim htmlTable As htmlTable
        Set IE = New InternetExplorerMedium
        'Set IE = CreateObject("InternetExplorer.Application")
        IE.Visible = True

        'Navigate to CSA tool Home Page
        IE.navigate "https://csa.abcdefg.com/Collector_view.aspx/"

        'Wait till it loads
        Do While IE.Busy
            Application.Wait DateAdd("s", 1, Now)
        Loop

        Set doc = CreateObject("htmlfile")
        Set doc = IE.document

        'Enter Invoice Number in SearchBy box
        doc.getElementById("ContentPlaceHolder1_ddlSearch").Value = "[Inv Number]"

        Range("A1").Select

        'Count the number of rows in the data list
        Dim X As Long
        Range("A1").Select
        X = Selection.End(xlDown).Row

        'For each invoice number the loop starts here
        For rowNo = 2 To X
            ActiveCell.Offset(1).Select
            'Fill Blue colour in active processing invoice number cell
            ThisWorkbook.Sheets("Data").Range("A" & rowNo).Interior.ColorIndex = 37

            'Input the invoice number
            doc.getElementById("ContentPlaceHolder1_txtSearch").Value = ThisWorkbook.Sheets("Data").Range("A" & rowNo).Value

            'Click the Search button
    'This is the Line1
            doc.getElementById("ContentPlaceHolder1_search").Click

            'Wait till it loads
            Do While IE.Busy
                Application.Wait DateAdd("s", 5, Now)
            Loop

            'Checkbox select all
    'This is the Line2
            doc.getElementById("ContentPlaceHolder1_GridView1_chkboxSelectAll").Click
            'Wait 3 seconds till it selects all the checkboxes
            Application.Wait DateAdd("s", 3, Now)

            'Enter rest of the data
            doc.getElementById("ContentPlaceHolder1_ddlaction").Value = ThisWorkbook.Sheets("Data").Range("B" & rowNo).Value        'Input Action
            doc.getElementById("ContentPlaceHolder1_txtToDoDate").Value = ThisWorkbook.Sheets("Data").Range("C" & rowNo).Value      'Input Action Date
            doc.getElementById("ContentPlaceHolder1_ddlstatus").Value = ThisWorkbook.Sheets("Data").Range("D" & rowNo).Value        'Input Root Cause
            doc.getElementById("ContentPlaceHolder1_txtcomments").Value = ThisWorkbook.Sheets("Data").Range("E" & rowNo).Value      'Input Comments
            doc.getElementById("ContentPlaceHolder1_btn_Comments").Click                                                            'Click Submit button

            Application.Wait DateAdd("s", 3, Now)

            'Hit enter on MessegeBox
            Application.SendKeys "{ENTER}"

            'Fill Green colour in the active cell when all entries are passed
            ThisWorkbook.Sheets("Data").Range("A" & rowNo).Interior.ColorIndex = 35

        Next 'Proceed to next invoice number

        IE.Quit 'Quit Internet explorer
        test2 = Timer
        MsgBox (X - 1) & " Invoices have been updated and it took " & Format((test2 - test1) / 86400, "hh:mm:ss") & " Seconds."

    End Sub

Ответы [ 3 ]

0 голосов
/ 25 марта 2019

Используйте правильные ожидания загрузки страницы после каждого .Navigate и .Click.

While ie.Busy Or ie.readyState < 4: DoEvents: Wend

Кроме того, вы можете обернуть элементы, которые выдают ошибки, связанные с таймингами, в синхронизированные циклы, которые пытаются установитьссылка на объект

Dim t As Date, ele As Object
Const MAX_WAIT_SEC As Long = 10

t = Timer
Do
    On Error Resume Next
    Set ele = doc.getElementById("ContentPlaceHolder1_GridView1_chkboxSelectAll")
    On Error GoTo 0
    If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While ele Is Nothing

If Not ele Is Nothing Then
    ele.Click
End If
0 голосов
/ 25 марта 2019

Я удалил ниже цикла ожидания после строки 1.

    'Wait till it loads
    Do While IE.Busy
        Application.Wait DateAdd("s", 5, Now)
    Loop

и добавлено исправление 10 секунд ожидания Application.Wait DateAdd("s", 10, Now) непосредственно перед

    doc.getElementById("ContentPlaceHolder1_GridView1_chkboxSelectAll").Click
    'Wait 3 seconds till it selects all the checkboxes
    Application.Wait DateAdd("s", 3, Now)

Итак, последний фрагмент кода, как показано ниже, и работает!

'This is the Line1
        doc.getElementById("ContentPlaceHolder1_search").Click

        'Checkbox select all
'This is the Line2
        Application.Wait DateAdd("s", 10, Now)
        doc.getElementById("ContentPlaceHolder1_GridView1_chkboxSelectAll").Click
        'Wait 3 seconds till it selects all the checkboxes
        Application.Wait DateAdd("s", 3, Now)
0 голосов
/ 24 марта 2019

пересмотрено в 2019-03-25

Я думаю, что ошибка выдается, потому что doc изменяется.

Перепишите

' This is the Line2
    doc.getElementById("ContentPlaceHolder1_GridView1_chkboxSelectAll").Click
    'Wait 3 seconds till it selects all the checkboxes
    Application.Wait DateAdd("s", 3, Now)

в

' This is the Line2 
    application.wait Application.Wait DateAdd("s", 1, Now)
    set doc = IE.document
    doc.getElementById("ContentPlaceHolder1_GridView1_chkboxSelectAll").Click
    'Wait 3 seconds till it selects all the checkboxes
    Application.Wait DateAdd("s", 3, Now)

может быть полезным.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...