Editing HTML Code using Excel VBA - html

I am in need of editing html code using VBA. I actually got this working as far as editing values of text boxes. My problem is that when I simulate clicking the "submit" button there are new tables that come up. The web address stays the same but now there is new html code generated for the tables. I am trying to read data from these tables but it seems as if they don't exist when I try and query them. So I am guessing that I need to update or refresh the IE html code after I press the "submit" button. I can not seem to figure out how to do this. Any help is greatly appreciated. Here is my code so far:
Sub ImportStackOverflowData()
Dim SearchFor As IHTMLElement
Dim RowNumber As Long
RowNumber = 4
'to refer to the running copy of Internet Explorer
Dim ie As InternetExplorer
'to refer to the HTML document returned
Dim html As HTMLDocument
'open Internet Explorer in memory, and go to website
Set ie = New InternetExplorer
ie.Visible = True
ie.Navigate "http://google.com"
'Wait until IE is done loading page
Do While ie.ReadyState <> READYSTATE_COMPLETE
Application.StatusBar = "Trying to go to TRSDataBase ..."
DoEvents
Loop
Set html = ie.Document
Application.StatusBar = ""
'clear old data out and put titles in
Cells.Clear
Set SearchFor = html.getElementById("ddl_process")
'if this is the tag containing the question details, process it
If SearchFor.ID = "ddl_process" Then
'Replace the value of dl-process with copperhead name
Call SearchFor.setAttribute("value", "CPHB_FAT")
Cells(RowNumber, 1).Value = "Successfully replaced ddl_process to : " &
SearchFor.getAttribute("value")
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
Set SearchFor = html.getElementById("txt_startdate")
If SearchFor.ID = "txt_startdate" Then
'Replace the value of dl-process with copperhead name
Call SearchFor.setAttribute("value", "07-07-17")
Cells(RowNumber, 1).Value = "Successfully replaced startdate to : " &
SearchFor.getAttribute("value")
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
Set SearchFor = html.getElementById("txt_enddate")
If SearchFor.ID = "txt_enddate" Then
'Replace the value of dl-process with copperhead name
Call SearchFor.setAttribute("value", "07-14-17")
Cells(RowNumber, 1).Value = "Successfully replaced enddate to : " &
SearchFor.getAttribute("value")
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
'find view button and click it
Set SearchFor = html.getElementById("btn_header")
If SearchFor.ID = "btn_header" Then
SearchFor.Click
Cells(RowNumber, 1).Value = "The View Button has been clicked."
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
'Now get data from table after it loads
Application.Wait (Now + TimeValue("0:00:20"))
Set html = ie.Document <----------This is where i am trying to update or refresh my code after it loads with the new tables
Debug.Print ie.Document.body.innerHTML
Range("L5").Value = ie.Document.getElementsByTag("table")
(1).Rows(1).Cells(2).innerText

Try getting a new pointer to the window. Sometimes that does the trick.
Public Function FindWindow(SearchBy As String, SearchCriteria As String) As Object
Dim Window As Object
For Each Window In CreateObject("Shell.Application").Windows
If SearchBy = "URL" And Window.LocationURL Like "*" & SearchCriteria & "*" Then
Set FindWindow = Window
Exit Function
ElseIf SearchBy = "Name" And Window.LocationName Like "*" & SearchCriteria & "*" Then
Set FindWindow = Window
Exit Function
End If
Next
Set FindWindow = Nothing
End Function
Sub getNewPointer()
Dim ie As InternetExplorer
ie.Navigate "www.google.com"
'Wait for the page to load and do actions etc
'Your code here
'
'
'Clear the IE reference
Set ie = Nothing
'get a new pointer to the window of interest
'Keep in mind it finds the first matching Window based on your criteria!
Set ie = FindWindow("URL", "www.google.ca")
'Try getting the property you want
Debug.Print
End Sub

Related

Extract the details from a Table using VBA gets object variable or with block variable not set

My script runs for few row and then i a getting object variable or with block variable not set error.
I am using the below script to extract the 5,6,7 value from the NSEIndia website.
I get the value of a stock from the same Excel and update the same excel with the values from the nseindia website.
Sub Stock_Basic_Update_NSE()
Dim ie As InternetExplorer
Dim webpage As HTMLDocument
Dim ws As Worksheet
For Item = 23 To 1505
Set ws = ThisWorkbook.Worksheets("NSE Stocks Details")
sSearch = ws.Range("A" & Item).Value
'sSearch = Filestk.Worksheets("Sheet1").Range("E1").Value
Set ie = New InternetExplorer
'ie.Visible = True
ie.navigate ("https://www.nseindia.com/get-quotes/equity?symbol=" & sSearch)
Do While ie.readyState = 4: DoEvents: Loop
Do Until ie.readyState = 4: DoEvents: Loop
While ie.Busy
DoEvents
Wend
Set webpage = ie.document
ws.Cells(Item, 3).Value = webpage.getElementsByClassName("eq-series table-fullwidth w-100")(0).getElementsByTagName("td")(5).innerText
ws.Cells(Item, 4).Value = webpage.getElementsByClassName("eq-series table-fullwidth w-100")(0).getElementsByTagName("td")(6).innerText
ws.Cells(Item, 5).Value = webpage.getElementsByClassName("eq-series table-fullwidth w-100")(0).getElementsByTagName("td")(7).innerText
ie.Quit
Set ie = Nothing
Next Item
End Sub
You had some errors in your code and you hadn't wait for the full document to load. Try the following code. I have commented it. So you can see, what I have changed and why. I have tried it with the top 50 symbols.
Sub Stock_Basic_Update_NSE()
'Declare always all variables
Dim ie As Object 'I switched this from early to late binding (not required)
Dim nodeTable As Object
Dim ws As Worksheet
Dim item As Long
Dim sSearch As String
'Use this outside the loop. You only need it once
Set ws = ThisWorkbook.Worksheets("NSE Stocks Details")
For item = 23 To 1505
sSearch = ws.Range("A" & item).Value
Set ie = CreateObject("internetexplorer.application")
ie.Visible = False
'Encode symbols that are restricted for using in URLs. Like &, : or ?
ie.navigate ("https://www.nseindia.com/get-quotes/equity?symbol=" & WorksheetFunction.EncodeURL(sSearch))
'It's not "While = 4" because 4 stands for "readystate = complete"
'If you want to use "= 4" you must use "Until" instead of "While"
'It doesn't matter what you use
Do While ie.readyState <> 4: DoEvents: Loop
'Manual break to load dynamic content after the IE reports the page load was complete
'This was your main problem
Application.Wait (Now + TimeSerial(0, 0, 2))
'The needed html table has an ID. If possible use always that instead of class names
'because an html ID is unique if the standard is kept
'Also use a variable to save the elements
'So you don't need to shorten the html document string in most cases because
'it's only needed one time
Set nodeTable = ie.document.getElementByID("equityInfo")
ws.Cells(item, 3).Value = nodeTable.getElementsByTagName("td")(5).innerText
ws.Cells(item, 4).Value = nodeTable.getElementsByTagName("td")(6).innerText
ws.Cells(item, 5).Value = nodeTable.getElementsByTagName("td")(7).innerText
'Clean up
ie.Quit
Set ie = Nothing
Next item
End Sub

Getting the text contents from a HTML Table without ID by using VBA

I am trying to parse a HTML table (it has no id but class name) from a website. However, since it has no id, I have difficulty in printing the contents from the table. But I couldn't figure it out.
Edited
Here you can see the image of Excel file. GTIP Numbers are located at column A. My aim is when the VBA code runs, these GTIP numbers from column A are forwarded to the Search Field named "GTİP Ara" in the website https://www.isib.gov.tr/urun-arama/. As a result, the companies having the selected GTIP will be returned to the columns next specified row.
For the third row, GTIP number "841013000000" has forwarded to the Search Field named GTIP Ara and as a result; Company 2, ... Company 9 are returned to neighbor columns.
Sometimes GTIP numbers return nothing since none of the companies are holding specified number.
For example: 841410819000 will return the companies but 841112101000 will return an error "Aradığınız Sonuç Bulunamadı!". That's why I am trying to add an if statement but it doesn't work properly.
Now, because of a mistake somewhere in my code block; the returned values are same for each GTIP, here you can see the result on second image.
Sub GrabLastNames()
Dim objIE As InternetExplorer
Dim ele As Object
Dim y As Integer
Set objIE = New InternetExplorer
objIE.Visible = True
objIE.navigate "https://www.isib.gov.tr/urun-arama"
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
y = 2
For i = 2 To 269
objIE.document.getElementById("gtip-ara").Value = _
Sheets("Sheet1").Range("A:A").Cells(i, 1).Value
objIE.document.getElementById("ara").Click
'If objIE.document.getElementsByClassName("error").getElementsByTagName("span").Value <> "Aradığınız Sonuç Bulunamadı!" Then
For Each ele In objIE.document.getElementsByClassName("urun-arama-table table")(0).getElementsByTagName("tbody")(0).getElementsByTagName("tr")
Sheets("Sheet1").Cells(i, y).Value = ele.Children(0).textContent
y = y + 1
Next
y = 2
Next i
End Sub
I only had one working GTIP 841410819000, so cant test this more thoroughly.
You don't really need to know the ID, the page has one table, so getting it using getElemenetsByClassName like you did, or just getElementsByTagName like in my example should work fine. My code is probably the same as yours, just with a few pauses to a: not spam the website, and b: give IE a chance to get itself together (its IE after all).
If you can provide a few more working GTIP values I can test a bit more.
' requires reference 'Microft HTML Object Library'
Sub Main()
Dim Browser As New InternetExplorer
Browser.Visible = True
Browser.navigate "https://www.isib.gov.tr/urun-arama"
Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
DoEvents
Loop
Dim Sheet As Worksheet: Set Sheet = ThisWorkbook.Worksheets("Sheet1")
Dim TableRows As IHTMLElementCollection
Dim TableRow As IHTMLElement
Dim SourceRow As Integer
Dim ResultColumn As Integer
Application.Wait (Now + TimeValue("0:00:05"))
SourceRow = 2 ' Skip Header
Do
Debug.Print "Trying " & Sheet.Cells(SourceRow, 1).Value
Browser.Document.getElementById("gtip-ara").Value = Sheet.Cells(SourceRow, 1).Value
Browser.Document.getElementById("ara").Click
Application.Wait (Now + TimeValue("0:00:02"))
Do While Browser.Busy
DoEvents
Loop
If Browser.Document.getElementsByTagName("table").Length > 0 Then
Debug.Print " > Found Results"
Set TableRows = Browser.Document.getElementsByTagName("table")(0).getElementsByTagName("tbody")(0).getElementsByTagName("tr")
ResultColumn = 2 ' dont overwrite search term
For Each TableRow In TableRows
Sheet.Cells(SourceRow, ResultColumn).Value = TableRow.innerText
ResultColumn = ResultColumn + 1
Next TableRow
Else
Debug.Print " - No Results Found"
End If
If Sheet.Cells(SourceRow + 1, 1).Value = "" Then
Exit Do
Else
SourceRow = SourceRow + 1
End If
Application.Wait (Now + TimeValue("0:00:05"))
Loop
Browser.Quit
Set Browser = Nothing
End Sub
Update
Updated my code again, it doesn't spawn lots of windows anymore and prints only the company name (as your example did).
' requires Microsoft HTML Object Library
' requires Microsoft XML, v6.0
Sub Main()
Dim XHR As XMLHTTP60
Dim Document As HTMLDocument
Dim ResultRows As IHTMLElementCollection
Dim ResultRow As IHTMLElement
Dim Sheet As Worksheet: Set Sheet = ThisWorkbook.Worksheets("Sheet1")
Dim SheetRow As Integer
Dim SheetColumn As Integer
Dim LastRow As Integer
LastRow = Sheet.Cells(Sheet.Rows.Count, "A").End(xlUp).Row
For SheetRow = 2 To LastRow
Debug.Print "Trying GTIP:" & Sheet.Cells(SheetRow, 1).Value
Application.StatusBar = "Status: " & Right(String(Len(CStr(LastRow - 1)), "0") & CStr(SheetRow - 1), Len(CStr(LastRow - 1))) & "/" & CStr(LastRow - 1)
Set XHR = New XMLHTTP60
XHR.Open "POST", "https://www.isib.gov.tr/urun-arama", False
XHR.setRequestHeader "content-type", "application/x-www-form-urlencoded"
XHR.send "gtipkategori=" & Sheet.Cells(SheetRow, 1).Value
Set Document = New HTMLDocument
Document.body.innerHTML = XHR.responseText
If Document.getElementsByTagName("table").Length > 0 Then
Debug.Print " > Found Results"
SheetColumn = 2 ' First Column to output data into
Set ResultRows = Document.getElementsByTagName("table")(0).getElementsByTagName("tbody")(0).getElementsByTagName("tr")
For Each ResultRow In ResultRows
Sheet.Cells(SheetRow, SheetColumn).Value = ResultRow.getElementsByTagName("td")(0).innerText ' 0 - company name
SheetColumn = SheetColumn + 1
Next
Else
Debug.Print " - No Results"
End If
Set XHR = Nothing
Set Document = Nothing
Application.Wait (Now + TimeValue("0:00:01")) ' slow down requests
Next
Application.StatusBar = "Complete"
End Sub

VBA - Extract data from html to excel

I am having a problem with coding. I used excel VBA to extract data from a webpage to excel. The webpage is https://proptx.midland.com.hk/utx/index.jsp?est_id=E12837&lang=en
Click "All transaction" and it displays a second table at the bottom of the first table. I would like to extract data from the bottom table (not the top one).
Here is the code:
Sub PropertyTransactions()
Dim ieObj As InternetExplorer
Dim htmlEle As IHTMLElement
Dim i As Integer
i = 1
Set ieObj = New InternetExplorer
ieObj.Visible = True
ieObj.navigate "https://proptx.midland.com.hk/utx/index.jsp?est_id=E12837&lang=en"
Application.Wait Now + TimeValue("00:00:05")
For Each htmlEle In ieObj.document.getElementsByClassName("tablesorter")(0).getElementsByTagName("tr")
Set htmlEle = ActiveDocument.all.tags("head").Item(0)
With ActiveSheet
.Range("A" & i).Value = htmlEle.Children(0).textContent
.Range("B" & i).Value = htmlEle.Children(1).textContent
.Range("C" & i).Value = htmlEle.Children(2).textContent
.Range("D" & i).Value = htmlEle.Children(3).textContent
.Range("E" & i).Value = htmlEle.Children(4).textContent
.Range("F" & i).Value = htmlEle.Children(5).textContent
.Range("G" & i).Value = htmlEle.Children(6).textContent
.Range("H" & i).Value = htmlEle.Children(7).textContent
.Range("I" & i).Value = htmlEle.Children(8).textContent
.Range("J" & i).Value = htmlEle.Children(9).textContent
End With
i = i + 1
Next htmlEle
End Sub
However, there is an error in this line:
For Each htmlEle In ieObj.document.getElementsByClassName("tablesorter")(0).getElementsByTagName("tr")
It displays a run-time error 91: object variable or with block variable not set. How can I fix it? Thank you very much!
I use late binding but that doesn't matter. Please read the comments in the macro:
Sub PropertyTransactions()
Dim url As String
Dim browser As Object
Dim nodeTransactionTab As Object
Dim nodeTransactionTable As Object
Dim nodesHeaderAll As Object
Dim nodeHeaderOne As Object
Dim nodesTrAll As Object
Dim nodeTrOne As Object
Dim nodesTdAll As Object
Dim nodeTdOne As Object
Dim currentRow As Long
Dim currentColumn As Long
'Initialize variables
currentRow = 1
currentColumn = 1
url = "https://proptx.midland.com.hk/utx/index.jsp?est_id=E12837&lang=en"
'Initialize Internet Explorer, set visibility,
'call URL and wait until page is fully loaded
Set browser = CreateObject("internetexplorer.application")
browser.Visible = True 'You can set this to False to make the IE invisible
browser.navigate url
Do Until browser.ReadyState = 4: DoEvents: Loop
'First we must click the 'All Transaction' tab to load the table you want
'The tab works like a button and has the id 'tx_record_3'
'The nature of an id is that it is unique
'With the following lines you can try to get elements by them ids
'The method getElementByID() doesn't build a node collection
'We switch off all runtime errors when we use it because we get
'a runtime error if there is nor element with that id
On Error Resume Next
Set nodeTransactionTab = browser.document.getElementByID("tx_record_3")
On Error GoTo 0
'Now we check if we have an html element 'nodeTransactionTab'
If Not nodeTransactionTab Is Nothing Then
'Click the tab and give a short break to load the transaction table
nodeTransactionTab.Click
Application.Wait Now + TimeValue("00:00:02")
'Now we can get the transaction table
'You try that with the css class 'tablesorter' but the table has also an id
'(The CSS class 'tablesorter' can also only be found after the transaction
'table has been loaded)
On Error Resume Next
Set nodeTransactionTable = browser.document.getElementByID("Tx_hist_table")
On Error GoTo 0
Else
'The object nodeTransactionTab couldn't be build
MsgBox "No transaction tab found"
End If
'To avoid deep if nesting, we can check at this point whether the transaction
'table was found, because an object is nothing by default
If Not nodeTransactionTable Is Nothing Then
'We trust the header is present
Set nodesHeaderAll = nodeTransactionTable.getElementsByTagName("th")
'Get header of transaction table
For Each nodeHeaderOne In nodesHeaderAll
ActiveSheet.Cells(currentRow, currentColumn).Value = Trim(nodeHeaderOne.innertext)
currentColumn = currentColumn + 1
Next nodeHeaderOne
'Prepare next line
currentRow = currentRow + 1
currentColumn = 1
'We trust the values are present too
'Get all value table rows
Set nodesTrAll = nodeTransactionTable.getElementsByTagName("tbody")(0).getElementsByTagName("tr")
'Get one row of values after the other from transaction table
For Each nodeTrOne In nodesTrAll
'Get all cells of next row
Set nodesTdAll = nodeTrOne.getElementsByTagName("td")
'Get values cell by cell
For Each nodeTdOne In nodesTdAll
ActiveSheet.Cells(currentRow, currentColumn).Value = Trim(nodeTdOne.innertext)
currentColumn = currentColumn + 1
Next nodeTdOne
'Prepare next line
currentRow = currentRow + 1
currentColumn = 1
Next nodeTrOne
Else
'The object nodeTransactionTable couldn't be build
MsgBox "No transaction table found"
End If
'Clean up
browser.Quit
Set browser = Nothing
Set nodeTransactionTab = Nothing
Set nodesHeaderAll = Nothing
Set nodeHeaderOne = Nothing
Set nodesTrAll = Nothing
Set nodeTrOne = Nothing
Set nodesTdAll = Nothing
Set nodeTdOne = Nothing
End Sub

Need Excel VBA to navigate website and download specific files

Trying to understand how to interact with a website in a specific way. This is part of a larger code I'm working on that will loop through a list of ContractorIDs. What I need to do from here is the following:
Navigate to this website: https://ufr.osd.state.ma.us/WebAccess/SearchDetails.asp?ContractorID=042786217&FilingYear=2018&nOrgPage=7&Year=2018
Find the link that says "UFR Filing with Audited Financials" and click on it. (if it's not there, end the sub)
On the ensuing page, find the link that is identified under "Document Category" as "UFR Excel Template" and click on it. (in this case, the link says "15-UFR18.xls", however since there's no consistent link naming scheme, the correct link will always have to be identified by the label under "Document Category" as mentioned. If the link doesn't exist, exit sub.)
On the ensuing page, click the "Download" link at the top and save the file under the following file path (which would be created at this time): C:\Documents\042786217\2018.
Edit: Code below gets me to the point where the download button is clicked, then I get the Open/Save/Cancel dialog box. Nearly there, just need to figure out how to save the file into a specific path.
Option Explicit
Sub UFRScraper()
If MsgBox("UFR Scraper will run now. Do you wish to continue?", vbYesNo) = vbNo Then Exit Sub
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
Dim ele As Object
Dim tbl_Providers As ListObject: Set tbl_Providers = ThisWorkbook.Worksheets("tbl_ProviderList").ListObjects("tbl_Providers")
Dim FEIN As String: FEIN = ""
Dim FEINList As Range: Set FEINList = tbl_Providers.ListColumns("FEIN").DataBodyRange
Dim ProviderName As String: ProviderName = ""
Dim ProviderNames As Range: Set ProviderNames = tbl_Providers.ListColumns("Provider Name").DataBodyRange
Dim FiscalYear As String: FiscalYear = ""
Dim urlUFRDetails As String: urlUFRDetails = ""
Dim i As Integer
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' Show (True)/Hide (False) IE
IE.Visible = True
i = 1
For i = 1 To 3 'Limited to 3 during testing. Change when ready.
FEIN = FEINList(i, 1)
ProviderName = ProviderNames(i, 1)
urlUFRDetails = "https://ufr.osd.state.ma.us/WebAccess/SearchDetails.asp?ContractorID=" & FEIN & "&FilingYear=2018&nOrgPage=1&Year=2018"
IE.Navigate urlUFRDetails
' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
'Step 2 is done here
Dim filingFound As Boolean: filingFound = False
For Each ele In IE.Document.getElementsByTagName("a")
If ele.innerText = "UFR Filing with Audited Financials" Then
filingFound = True
IE.Navigate ele.href
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
Exit For
End If
Next ele
If filingFound = False Then
GoTo Skip
End If
'Step 3
Dim j As Integer: j = 0
Dim UFRFileFound As Boolean: UFRFileFound = False
For Each ele In IE.Document.getElementsByTagName("li")
j = j + 1
If ele.innerText = "UFR Excel Template" Then
UFRFileFound = True
IE.Navigate "https://ufr.osd.state.ma.us/WebAccess/documentviewact.asp?counter=" & j - 4
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
Exit For
End If
Next ele
If UFRFileFound = False Then
GoTo Skip
End If
'Step 4
IE.Document.getElementById("LinkButton2").Click
'**Built in wait time to avoid accidentally overloading server with repeated quick requests during development and testing**
Skip:
Application.Wait (Now + TimeValue("0:00:03"))
MsgBox "Loop " & i & " complete."
Next i
'Unload IE
IE.Quit
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
MsgBox "Process complete!"
End Sub
I have tried step 3 with some what lengthy way. but could not provide complete download code as (after one successful manual attempt) at present even manual download attempt causing massage "The File Could Not Be Retrieved" (maybe server side constrain)
Code only take you down to the cell containing href of the xlx file
Dim doc As HTMLDocument
Dim Tbl As HTMLTable, Cel As HTMLTableCell, Rw As HTMLTableRow, Col As HTMLTableCol
Set doc = IE.document
For Each ele In IE.document.getElementsByClassName("boxedContent")
For Each Tbl In ele.getElementsByTagName("table")
For Each Rw In Tbl.Rows
For Each Cel In Rw.Cells
'Debug.Print Cel.innerText
If InStr(1, Cel.innerText, "UFR Excel Template") > 0 Then
Debug.Print Rw.Cells(2).innerText & " - " & Rw.Cells(2).innerHTML
End If
Next
Next Rw
Next Tbl
Next
Once the href is available PtrSafe Function or WinHTTPrequest or other methods could be used to download the file. Welcome and eager to learn some more efficient answers in this case from experts like #QHarr and others.

Select option from Internet Explorer dropdown list

I am working on opening a webpage and filling out some fields. I managed to fill textboxes, but I am having trouble selecting options from drop down lists checking/selecting radio buttons.
This is the HTML code referring to the dropdown list:
HTML code for drop down list
This one is the code for one of the radio buttons:
HTML code for radio button
This is my code so far:
Sub w()
'
' w Macro
'
' Keyboard Shortcut: Ctrl+w
'
'pick ups cell b2 value
Dim cellvalue As String
cellvalue = ActiveSheet.Cells(1, 2)
Dim HTMLDoc As HTMLDocument
Dim oBrowser As InternetExplorer
''Sub Login_2_Website()
Dim oHTML_Element As IHTMLElement
Dim sURL As String
On Error GoTo Err_Clear
sURL = cellvalue '
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True
Do
' Wait till the Browser is loaded
Loop Until oBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = oBrowser.document
'fill email response address
HTMLDoc.all.emailAddresses.Value = ActiveSheet.Cells(5, 3)
'fill shipment reference number
HTMLDoc.all.filingRefNumber.Value = ActiveSheet.Cells(5, 7)
'fill dropbox option
'NOT WORKING
If Not VBA.IsNull(ie.document.getElementById("select2-drop-mask")) Then
Dim htmlSelect
Set htmlSelect = ie.document.getElementById("select2-drop-mask")
htmlSelect.Value = 4 - POSTDEPARTURE
Else
MsgBox "Element 'select2-drop-mask' was not found", vbExclamation
End If
'SELECT RADIO BUTTON
' NOT WORKING
ie.document.getElementsByName("shipmentInfo.routedExpTransactionInd.stringFiEld").Item(1).Checked = True
For Each oHTML_Element In HTMLDoc.getElementsByTagName("Login")
If oHTML_Element.Type = "Login" Then oHTML_Element.Click: Exit For
Next
' oBrowser.Refresh ' Refresh If Needed
Err_Clear:
If Err <> 0 Then
'Debug.Assert Err = 0
Err.Clear
Resume Next
End If
End Sub
With respect to your list/dropdown, I think there are two potential solutions.
Change to
htmlSelect.Value = "4 - POSTDEPARTURE"
Refer to the index value. I.e. if it's the first item in the dropdown, it's item(0).
htmlSelect.item(0).selected="True"
For your radio button, wrap 'true' in quotes. Also you'd need to loop through all elements with that particular name (getElementbyID only returns 1 item, but getElementsByName can refer to multiple elements).
e.g.
dim objects
dim obj
set objects=document.getElementsByName("shipmentInfo.routedExpTransactionInd.stringFiEld")
for each obj in objects
obj.item(0).checked=True
next
or try:
Set ieRadio = IE.Document.all
ieRadio.Item("shipmentInfo.routedExpTransactionInd.stringFiEld")(1).Checked = True