As I’ve commented before, can do using libraries Microsoft HTML Object and Microsoft XML, V6.0. They need to be referenced within the VBA (in the code window, access the menu Ferramentas -> Referências
and mark these libraries:
![inserir a descrição da imagem aqui](https://i.stack.imgur.com/JVohr.png)
Then, you need to parse the HTML/Javascript code of the page with the form of interest to find out:
- What are the fields and values needed to send the request
- What is the request method (POST or GET, for example)
- What is the address of
action
form (if empty, is the page address with the form)
So, build a code something like this:
Sub GenMegaSenaNumbers()
On Error Resume Next
Dim oHttp As MSXML2.XMLHTTP60
Dim oDoc As MSHTML.HTMLDocument
Dim oText As HTMLParaElement
Dim sURL As String
Dim sParameters As String
' Defina aqui a URL da página de requisição do formulário
sURL = "https://www.random.org/quick-pick/index.php"
' Defina aqui os parâmetros para a consulta
' (usando EXATAMENTE os mesmos nomes dos campos no formulário)
sParameters = "tickets=1&lottery=6x60.0x0"
' Faz a consulta dos dados
Cells(1, 1) = "Aguarde. Fazendo a consulta pelos números do jogo..."
Set oHttp = New MSXML2.XMLHTTP60
oHttp.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
oHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
oHttp.Open "GET", sURL & "?" & sParameters, False
oHttp.send
' Se o método de acesso for POST ao invés de GET, use assim:
'oHttp.Open "POST", sURL, False
'oHttp.send sParameters
' Checa se o carregamento foi efetuado corretamente
If oHttp.Status <> 200 Then
Cells(1, 1) = "Oops! Não foi possível obter a resposta! Erro: (" & Str(oHttp.Status) & " )" & oHttp.statusText
Exit Sub
End If
' Obtem a resposta
Set oDoc = New MSHTML.HTMLDocument
oDoc.body.innerHTML = oHttp.responseText
' E lê o dado do elemento desejado
Set oText = oDoc.getElementsByClassName("data").Item(0)
Cells(1, 1) = "Sugestão de jogo para a Mega-Sena: " & oText.innerText
End Sub
Sub Botão1_Click()
GenMegaSenaNumbers
End Sub
This example has a macro (the sub Botão1_Click
) attached to a button that executes the sub GenMegaSenaNumbers
, who is in fact responsible for making the request and getting the answer. In this example I refer to random number generation for a Mega-Sena game, free service available through Random.org. The form on this page has several fields (including a hidden one that is dynamically mounted by Javascript), but I used the Google Chrome developer tool, on the flap Network, to identify which parameters he sent in the request (much easier! and I could see that not all fields were needed).
Note that there is difference in the way to pass the parameters in VBA if the method is POST or GET (in the case of example, it was GET). Also note the parameter False
in the call for oHttp.Open
(third parameter, which does not exist in the original SOEN response that I mentioned in the comments). It indicates that the call is not asynchronous, and so it is not necessary to tie the DoEvents
to wait for the result (Excel itself manages this for you, making the call synchronous).
Here is the screenshot of the result:
![inserir a descrição da imagem aqui](https://i.stack.imgur.com/aBHJX.png)
IMPORTANT REMARK: Naturally this method doesn’t work
with forms that require validation by CAPTCHA. After all, it is
precisely this the intention of a (good) CAPTCHA: prevent automatisms
run on the page. To understand (if you need to), read
more about the Wikipedia and right here at SOPT(suggestion of
reading 1 and reading suggestion 2). Independently, the
ideal (and probably legal) solution is to use a Web Service whenever available.
The consumption of Web Services in newer versions of Excel is fairly simple.
Hello. I’m running out of time to test and try to come up with an answer. But take a look on that Soen thread with another solution (without using the browser). It may be of some help. :)
– Luiz Vieira
Thanks Luiz... I’ll test and tell you.. Abs
– Márcio
Luiz, I took a look at this link, but I didn’t understand it very well. If I could help me later with this, I’m grateful. Abs
– Márcio
I would use the imacros (http://imacros.net) in firefox (https://addons.mozilla.org/pt-BR/firefox/addon/imacros-for-firefox/). You SAVE the actions and then execute.
– Eduardo Santana
Márcio, the article that thevieira pointed out is very interesting because the question person this with a problem relatively similar to yours and the person who answered showed that it is much easier to use MSXML2.XMLHTTP to send a request to the page and get the answer in an MSHTML.Htmldocument and read the data from within that MSHTML.
– vianna77
@Márcio is possible to do all this yes, but we need you to provide a picture of the spreadsheet or the complete code you were able to create... How do you indicate which Cnpjs should be accessed? You already put the entire CNPJ list on a sheet or you want to manually put one by one?
– Paulo Roberto
Paulo Roberto, good afternoon! I haven’t actually created the spreadsheet yet, but the idea is to create a spreadsheet with about 40 CNPJ’s, and create a hyperlink in each of them... Once you click it already accesses the site, searches the CNPJ and returns the information in Excel. Or if possible, click a button and search several CNPJ’s at once. The code I was able to elaborate is posted above. I am very grateful if you can help me. Thank you! Márcio
– Márcio
Oi Márcio. This service is paid, isn’t it? You don’t have access to web service of them (cited on this page: http://www.serasaexperian.com.br/consults/validationpersonalinformationlegal/pme-meios-access.html)?
– Luiz Vieira
This is very complicated, I tried to look too, but there was a block by Captcha (those security images) that prevented the search to proceed. That’s why they charge for this search and block access. It will be difficult, but if you get congratulations!
– wcj
The guy "created" the code exactly like this one here http://excelevba.com.br/fazer-login-em-um-site-usando-vba/ and then couldn’t create anything else?? I think some people lack humility.
– Evilmaax