Adding data to a Webpage

cpalvar

New Member
Joined
May 3, 2019
Messages
4
Hello,
I am trying to add data into a webpage , with vba. I can pass the values correctly but they are not saved
the following code passes the values correctly :

Code:
Dim desc as string, nLinha as integer
desc =" first of 4  invoice lines to be added"

for nLinha= 0 to 3  
      ie.Document.getElementById("sales_invoice_line_items_attributes_" & nLinha & "_description").Value = desc
next

if I do it manualy right after I press the character "f", wich is the first character of the variable string "desc", some event is triggered and a new empty line is added for data entry, but if i do it as in the above code with VBA, the value is entered but the event is not happening, the new empty line not created and the data is not stored

So far I tried to create an event that simulates manual data entry like this :
:

Code:
Dim ieEvent
Dim htmldoc as HTMLDocument
Set htmldoc = ie.Document

for nLinha= 0 to 3
      ie.Document.getElementById("sales_invoice_line_items_attributes_" & nLinha &     "_description").Value = desc

     Set ieEvent = htmldoc.createEvent("HTMLEvents")
     ieEvent.initEvent "change", False, True ' tambien probe con "keypress"
     ie.document.all.Item("sales_invoice_line_items_attributes_" & nLinha & "_description").dispatchEvent ieEvent

next


and still it does not work.
Any thoughts about this ?
 

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.
Welcome to MrExcel forums.

It's really impossible to help you without access to the web page, so I can only offer some general tips.

Move the createEvent and initEvent lines above the For loop - this only needs to be done once. Make sure the HTMLDocument is fully loaded before executing these lines.

You mention "keypress" in your code, so try adding a keypress event and invoking it for each character in the desc string, and invoke the "change" event after this loop.

Try fireEvent instead of dispatchEvent. The equivalent is just element.fireEvent "keypress".

Insert some pauses, using the Sleep API, to allow the web page to respond and process your inputs.

Using the browser's DOM explorer (F12 key) look for events on the parent elements of the element in question, i.e. elements higher up in the HTML hierarchy. You may need to trigger these events too.

Altogether, the code might look like this:
Code:
#If VBA7 Then
    Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
[URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=Else]#Else[/URL] 
    Private Declare Sub Sleep Lib "kernel32" (ByVal milliseconds As Long)
[URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=End]#End[/URL]  If

Sub Test()

    Dim changeEvent As Object
    Dim htmldoc as HTMLDocument
    Set htmldoc = ie.Document

    Stop 'ensure page is fully loaded before continuing
    Set changeEvent = htmldoc.createEvent("HTMLEvents")
    changeEvent.initEvent "change", True, False

    Dim keypressEvent As Object
    Set keypressEvent = HTMLdoc.createEvent("KeyboardEvent")
    keypressEvent.initEvent "keypress", True, False

    Dim i As Long
    Dim elem As Object 'use correct data type for tag/element, not Object

    for nLinha= 0 to 3
        set elem = HTMLDoc.getElementById("sales_invoice_line_items_attributes_" & nLinha &  "_description")
        
        elem.focus
        elem.Value = ""
        for i = 1 to len(desc)
            elem.Value = elem.Value & Mid(desc,i,1)
            elem.dispatchEvent keydownEvent
            DoEvents
            Sleep 100
        Next
        
        elem.dispatchEvent changeEvent
        DoEvents
        Sleep 250
        
    next

End Sub
PS - please use CODE tags when posting VBA code - click the # icon in the message editor.
 
Upvote 0
John,
Great help you provided, but I must confess I am a complete newbie with these automation procedures, so it is very dificult to understand what to do . I tried your code and still is not saving the data. I also noticed that when adding data manualy a calculation takes place after the element "unit_price" is entered, wich is not happening with VBA.

Do you think you can look at the page ? it has a login and password, but there is only dummy data, and it is an invoicing demo.

pls let me know if it's ok.
Thanks a lot
 
Upvote 0
Who is alsopp123?

OK, send me the URL and login details and describe exactly which bits you need to be automated.

PS - you've reached your PM quota so need to clear your Inbox.
 
Last edited:
Upvote 0
Hello John,
I dont know who is alsopp123
Any way, I solved only part of the problem, wich was that a random id was being generated after the first record, so I did this :
Code:
For Each ele In ie.Document.getElementsByTagName("input")
       If InStr(ele.Name, "sales_invoice[line_items_attributes]") > 0 Then
           If InStr(ele.Name, "][id]") > 0 Then            
                   nuevoID = ele.Name
           End If
       End If  
 Next

now I can fill in all the fields and records, but still the same issue with not triggering the events that save data
I have a form in Ms access with a command button that open the web page, enter data in the main form, enters all the lines od data in the child form, and in the end upon submission of the the error pops up due, because the child records are not updated


https://www.dropbox.com/sh/5u3xxd5wg79gwm5/AAAM0YaVJ8Fm0KSrB4QST-zua?dl=0
 
Upvote 0
All I wanted to do was solved with the great help of John_w, who was so kind to write the code to do it, and that I think we should share for the benefit of others

in order to trigger the events with VBA:

Code:
Set inputElement = HTMLdoc.getElementById("sales_invoice_line_items_attributes_" & nuevoID & "_description")
            inputElement.scrollIntoView
            inputElement.focus
            inputElement.Value = ""
            inputText = desc    ‘ String to be added
            For i = 1 To Len(inputText)
                inputElement.Value = inputElement.Value & Mid(inputText, i, 1)
                inputElement.dispatchEvent keypressEvent
                DoEvents
                Sleep 10
            Next
            inputElement.dispatchEvent changeEvent

before moving to the next record and since there is a random ID, it has to be retrieved , so that the second and subsequent lines are identified :

Code:
For Each inputElement In HTMLdoc.getElementsByTagName("input")
                'Debug.Print inputElement.Type, inputElement.id
                If inputElement.id Like "sales_invoice_line_items_attributes_*_description" Then
                    nuevoID = inputElement.id
                End If
            Next
            nuevoID = Replace(nuevoID, "sales_invoice_line_items_attributes_", "")
            nuevoID = Replace(nuevoID, "_description", "")
            Debug.Print nuevoID

In the end , looking for the button that submits the form and click it :

Code:
Set buttons = HTMLdoc.getElementsByTagName("BUTTON")
    Set finaliseButton = Nothing
    i = 0
    While i < buttons.length And finaliseButton Is Nothing
        If buttons(i).innerText = "Finalizar fatura" Then Set finaliseButton = buttons(i)
        i = i + 1
    Wend
    
    If Not finaliseButton Is Nothing Then
        finaliseButton.Click
        While IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE: DoEvents: Sleep 200: Wend
        While HTMLdoc.ReadyState <> "complete": DoEvents: Sleep 200: Wend
    Else
        MsgBox "'Finalizar fatura' button not found"
    End If

John, I dont know if you were able to read my last private message. I had to empty again my inbox folder again
Thanks so much for your help
 
Upvote 0

Forum statistics

Threads
1,223,696
Messages
6,173,891
Members
452,536
Latest member
Chiz511

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top