Vídeo recomendado
https://youtu.be/diWPPPhW-9E
https://youtu.be/diWPPPhW-9E
Interação VBA com Internet Explorer (dúvidas)
-
- Acabou de chegar
- Mensagens: 2
- Registrado em: Qui Jul 28, 2016 12:28 pm
Re: Interação VBA com Internet Explorer (dúvidas)
Apenas para critério de conhecimento vou compartilhar uma informação que não estava descrita em outros lugares que procurei e devido a ela eu acreditava que meu código estava errado, na automatização da página que estou tratando ela ela abria uma nova janela e fechava (mas deveria iniciar um download). Isso acontecia pois não foi liberado uma regra de segurança do Internet Explorer, para libera-lá é necessário ir no seguinte local dentro do Internet Explorer: Ferramentas > Opções da Internet > Segurança > Nível Personalizado > Download > Aviso automático para download de arquivo (Habilitar)
Pronto com esta configuração o IE irá permitir que a Janela de Download apareça para o usuário em um processo automático.
Agora estou apenas querendo aperfeiçoar a manipulação desta janela de download já que é necessário que ela esteja em "Primeiro Plano" para ser tratada pelo código abaixo que irá "salvar como" e substituir por outro arquivo caso necessário (quero que ela funcione em segundo plano):
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal param As Long) As Long
Public Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Sub AutoHoraHora()
Dim btnInput As Object ' MSHTML.HTMLInputElement
Dim ElementCol As Object ' MSHTML.IHTMLElementCollection
Dim IE As InternetExplorer
Dim C
Dim ULogin As Boolean, ieForm
Dim MyPass As String, MyLogin As String
MyLogin = ActiveWorkbook.Sheets("Plan1").Cells(1, 2).Value
MyPass = ActiveWorkbook.Sheets("Plan1").Cells(2, 2).Value
Set IE = New InternetExplorer ' Nova Página
IE.Visible = True
MySite = "http://xxxxxxxxxxxx.xxxxx.xxx.xx/xxxxx/login.jsp"
IE.Navigate MySite 'Acessar link
Do Until IE.ReadyState = READYSTATE_COMPLETE 'Loop ate conectar na página
Loop
IE.Document.all("login_txt").innerText = MyLogin 'Colocar Usuário
IE.Document.all("senha_txt").innerText = MyPass 'Colocar Senha
IE.Document.all("submit").Click 'Clicar para acessar
Do Until IE.ReadyState = READYSTATE_COMPLETE 'Loop ate conectar na página
Loop
Sleep (1000)
MySite = "http://xxxxxxxxxxxx.xxxxx.xxx.xx/xxxxx/ ... edidos.jsp"
IE.Navigate MySite
Do Until IE.ReadyState = READYSTATE_COMPLETE 'Loop ate conectar na página
Loop
hoje = Format(Now, "dd/mm/yyyy")
ontem = Format(Now - 30, "dd/mm/yyyy")
IE.Document.all("BeginDate").innerText = ontem 'Colocar Usuário
IE.Document.all("EndDate").innerText = hoje 'Colocar Senha
Sleep (5000)
'Identifica e Clica no Botão
Set ElementCol = IE.Document.getElementsByTagName("input")
For Each btnInput In ElementCol
If btnInput.Value Like "Extrair" Then ' não usado
btnInput.Focus
'Application.SendKeys "{ENTER}", True
winHwnd = FindWindow(vbNullString, "Cabeçalho da Página")
If winHwnd <> 0 Then
AppActivate "Windows Internet Explorer"
Application.SendKeys "{ENTER}", True
End If
btnInput.Click
'---Controlar a Janela de Download---------------
tempoinicial = TimeValue(Now)
tempofinal = tempoinicial + TimeValue("00:01:00")
While TimeValue(Now) < tempofinal
winHwnd = FindWindow(vbNullString, "Download de Arquivos")
'espera alguns segundos para substituir um arquivo já existente
If winHwnd <> 0 Then
Sleep (3000)
Application.SendKeys "%S", True
Sleep (3000)
Application.SendKeys "%L", True
Sleep (3000)
Application.SendKeys "%S", True
Application.SendKeys "%S", True
End If
Wend
'-----------------------------------------------
Exit For
End If
Next btnInput
IE.Quit
Set IE = Nothing
Do Until regra = 1
regra = IsWindowVisible(winHwnd)
Loop
Call VAI
ActiveWorkbook.Close
End Sub
Pronto com esta configuração o IE irá permitir que a Janela de Download apareça para o usuário em um processo automático.
Agora estou apenas querendo aperfeiçoar a manipulação desta janela de download já que é necessário que ela esteja em "Primeiro Plano" para ser tratada pelo código abaixo que irá "salvar como" e substituir por outro arquivo caso necessário (quero que ela funcione em segundo plano):
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal param As Long) As Long
Public Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Sub AutoHoraHora()
Dim btnInput As Object ' MSHTML.HTMLInputElement
Dim ElementCol As Object ' MSHTML.IHTMLElementCollection
Dim IE As InternetExplorer
Dim C
Dim ULogin As Boolean, ieForm
Dim MyPass As String, MyLogin As String
MyLogin = ActiveWorkbook.Sheets("Plan1").Cells(1, 2).Value
MyPass = ActiveWorkbook.Sheets("Plan1").Cells(2, 2).Value
Set IE = New InternetExplorer ' Nova Página
IE.Visible = True
MySite = "http://xxxxxxxxxxxx.xxxxx.xxx.xx/xxxxx/login.jsp"
IE.Navigate MySite 'Acessar link
Do Until IE.ReadyState = READYSTATE_COMPLETE 'Loop ate conectar na página
Loop
IE.Document.all("login_txt").innerText = MyLogin 'Colocar Usuário
IE.Document.all("senha_txt").innerText = MyPass 'Colocar Senha
IE.Document.all("submit").Click 'Clicar para acessar
Do Until IE.ReadyState = READYSTATE_COMPLETE 'Loop ate conectar na página
Loop
Sleep (1000)
MySite = "http://xxxxxxxxxxxx.xxxxx.xxx.xx/xxxxx/ ... edidos.jsp"
IE.Navigate MySite
Do Until IE.ReadyState = READYSTATE_COMPLETE 'Loop ate conectar na página
Loop
hoje = Format(Now, "dd/mm/yyyy")
ontem = Format(Now - 30, "dd/mm/yyyy")
IE.Document.all("BeginDate").innerText = ontem 'Colocar Usuário
IE.Document.all("EndDate").innerText = hoje 'Colocar Senha
Sleep (5000)
'Identifica e Clica no Botão
Set ElementCol = IE.Document.getElementsByTagName("input")
For Each btnInput In ElementCol
If btnInput.Value Like "Extrair" Then ' não usado
btnInput.Focus
'Application.SendKeys "{ENTER}", True
winHwnd = FindWindow(vbNullString, "Cabeçalho da Página")
If winHwnd <> 0 Then
AppActivate "Windows Internet Explorer"
Application.SendKeys "{ENTER}", True
End If
btnInput.Click
'---Controlar a Janela de Download---------------
tempoinicial = TimeValue(Now)
tempofinal = tempoinicial + TimeValue("00:01:00")
While TimeValue(Now) < tempofinal
winHwnd = FindWindow(vbNullString, "Download de Arquivos")
'espera alguns segundos para substituir um arquivo já existente
If winHwnd <> 0 Then
Sleep (3000)
Application.SendKeys "%S", True
Sleep (3000)
Application.SendKeys "%L", True
Sleep (3000)
Application.SendKeys "%S", True
Application.SendKeys "%S", True
End If
Wend
'-----------------------------------------------
Exit For
End If
Next btnInput
IE.Quit
Set IE = Nothing
Do Until regra = 1
regra = IsWindowVisible(winHwnd)
Loop
Call VAI
ActiveWorkbook.Close
End Sub
Re: Interação VBA com Internet Explorer (dúvidas)
Galera vi que este tópico tem muito haver com minha duvida, mas mesmo estudando os casos e soluções apresentadas acima, continuo não conseguindo logar em uma determinada página. não sei o que acontece mas já tentei os 2 modelos abaixo:
objIE.Document.all("loginview_textfield_username").innertext = Dc_Usuario
objIE.Document.all("loginview_passwordfield_password").innertext = Dc_Senha
objIE.Document.getElementsByTagName("loginview_textfield_username").innertext = Dc_Usuario
objIE.Document.getElementsByTagName("loginview_passwordfield_password").innertext = Dc_Senha
Nenhum dos 2 modos acima funciona para preencher o campo usuário e senha.
Sempre apresenta o mesmo erro descrito abaixo:
Erro em tempo de execução '-2147023179 (800706b5)':
Erro de automação
Interface desconhecida
Hoje meu código esta desta forma:
Sub LoginViaBrowser()
Dim Dc_Usuario As String
Dim Dc_Senha As String
Dim Dc_URL As String
Dim objIE As New InternetExplorer 'Referencie "Microsoft Internet Controls"
'Abre o IE
objIE.Visible = True
'Define os dados de acesso e link da página de login
Dc_Usuario = "xxxxx.xxxx"
Dc_Senha = "xxxxxx"
Dc_URL = "http://10.58.182.234:8081/dr_routingadmin_pu/"
'Navega até o link informado
objIE.Navigate2 Dc_URL
newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 5
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime
'(name) do elemento input do site que irá logar
objIE.Document.all("loginview_textfield_username").innertext = Dc_Usuario
objIE.Document.all("loginview_passwordfield_password").innertext = Dc_Senha
'(name) do formulário a ser submetido
objIE.Document.all("login").submit
End Sub
Podem me ajudar com este tipo de situação?
A página que quero acessar e inserir os dados para login, quando mando inspecionar objeto tenho o seguinte código.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=11;chrome=1" />
<title>Avaya Dynamic Routing</title>
<style type="text/css">html, body {height:100%;margin:0;}</style>
<link rel="shortcut icon" type="image/vnd.microsoft.icon" href="./VAADIN/themes/avaya/favicon.ico" />
<link rel="icon" type="image/vnd.microsoft.icon" href="./VAADIN/themes/avaya/favicon.ico" />
</head>
<body scroll="auto" class=" v-generated-body">
<div id="drroutingadminpu-1958229476" class=" v-app avaya">
<div class=" v-app-loading"></div>
<noscript>
You have to enable javascript in your browser to use an application built with Vaadin.
</noscript>
</div>
<script type="text/javascript" src="./VAADIN/vaadinPush.js"></script>
<script type="text/javascript" src="./VAADIN/vaadinBootstrap.js"></script>
<script type="text/javascript">//<![CDATA[
if (!window.vaadin) alert("Failed to load the bootstrap javascript: ./VAADIN/vaadinBootstrap.js");
vaadin.initApplication("drroutingadminpu-1958229476",{"heartbeatInterval":300,"versionInfo":{"vaadinVersion":"7.3.10"},"vaadinDir":"./VAADIN/","authErrMsg":{"message":"Take note of any unsaved data, and <u>click here<\/u> or press ESC to continue.","caption":"Authentication problem"},"widgetset":"com.avaya.ept.dr.AppWidgetSet","theme":"avaya","comErrMsg":{"message":"Take note of any unsaved data, and <u>click here<\/u> or press ESC to continue.","caption":"Communication problem"},"serviceUrl":".","standalone":true,"sessExpMsg":{"message":"Take note of any unsaved data, and <u>click here<\/u> or press ESC key to continue.","caption":"Session Expired"}});
//]]></script>
<script type="text/javascript">
function reCiF(i){var f = document.getElementById(i);if(f!=null){f.style.overflow='hidden';var val=f.value;f.value='';f.value=val;f.style.height='0px';f.style.height = (f.scrollHeight+1)+'px';} else {console.log('the field with id ['+i+'] was not found');}}
function adClR_s(id){var eventHandler = function(){reCiF(id);};var element=document.getElementById(id);element.onkeyup=eventHandler;}
function configureSegmTableMxN(rules, dims){var start = new Date().getTime();for(var i=1;i<=rules;i++){ addResizeListenerToRow(i,dims);}console.log('time taken to add all listeners '+(new Date().getTime()-start))}
function addResizeListenerToRow(rowNumber, dims){ for(var k=1;k<=dims;k++){ var id=rowNumber+'#'+k; adClR_s(id); }}
function resizeSegmTableMxN(rules,dims){var start = new Date().getTime();for(var i=1;i<=rules;i++){ for(var k=1;k<=dims;k++){ var id=i+'#'+k; reCiF(id); }}console.log('time taken to refresh all fields '+(new Date().getTime()-start))}
/*! Copyright © 2015 Zeno Rocha clipboard.js v1.5.2 https://zenorocha.github.io/clipboard.js Licensed MIT © Zeno Rocha */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,r){function o(a,c){if(!n[a]){if(!e[a]){var s="function"==typeof require&&require;if(!c&&s)return s(a,!0);if(i)return i(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var l=n[a]={exports:{}};e[a][0].call(l.exports,function(t){var n=e[a][1][t];return o(n?n:t)},l,l.exports,t,e,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(t,e,n){var r=t("matches-selector");e.exports=function(t,e,n){for(var o=n?t:t.parentNode;o&&o!==document;){if(r(o,e))return o;o=o.parentNode}}},{"matches-selector":2}],2:[function(t,e,n){function r(t,e){if(i)return i.call(t,e);for(var n=t.parentNode.querySelectorAll(e),r=0;r<n.length;++r)if(n[r]==t)return!0;return!1}var o=Element.prototype,i=o.matchesSelector||o.webkitMatchesSelector||o.mozMatchesSelector||o.msMatchesSelector||o.oMatchesSelector;e.exports=r},{}],3:[function(t,e,n){function r(t,e,n,r){var i=o.apply(this,arguments);return t.addEventListener(n,i),{destroy:function(){t.removeEventListener(n,i)}}}function o(t,e,n,r){return function(n){var o=i(n.target,e,!0);o&&(Object.defineProperty(n,"target",{value:o}),r.call(t,n))}}var i=t("closest");e.exports=r},{closest:1}],4:[function(t,e,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.function=function(t){var e=Object.prototype.toString.call(t);return"[object Function]"===e}},{}],5:[function(t,e,n){function r(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!c.string(e))throw new TypeError("Second argument must be a String");if(!c.function(n))throw new TypeError("Third argument must be a Function");if(c.node(t))return o(t,e,n);if(c.nodeList(t))return i(t,e,n);if(c.string(t))return a(t,e,n);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function o(t,e,n){return t.addEventListener(e,n),{destroy:function(){t.removeEventListener(e,n)}}}function i(t,e,n){return Array.prototype.forEach.call(t,function(t){t.addEventListener(e,n)}),{destroy:function(){Array.prototype.forEach.call(t,function(t){t.removeEventListener(e,n)})}}}function a(t,e,n){return s(document.body,t,e,n)}var c=t("./is"),s=t("delegate");e.exports=r},{"./is":4,delegate:3}],6:[function(t,e,n){function r(t){var e;if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName)t.select(),e=t.value;else{var n=window.getSelection(),r=document.createRange();r.selectNodeContents(t),n.removeAllRanges(),n.addRange(r),e=n.toString()}return e}e.exports=r},{}],7:[function(t,e,n){function r(){}r.prototype={on:function(t,e,n){var r=this.e||(this.e={});return(r[t]||(r[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){function r(){o.off(t,r),e.apply(n,arguments)}var o=this;return r._=e,this.on(t,r,n)},emit:function(t){var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),r=0,o=n.length;for(r;o>r;r++)n[r].fn.apply(n[r].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),r=n[t],o=[];if(r&&e)for(var i=0,a=r.length;a>i;i++)r.fn!==e&&r.fn._!==e&&o.push(r);return o.length?n[t]=o:delete n[t],this}},e.exports=r},{}],8:[function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}n.__esModule=!0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=t("select"),c=r(a),s=function(){function t(e){o(this,t),this.resolveOptions(e),this.initSelection()}return t.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action=e.action,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""},t.prototype.initSelection=function t(){if(this.text&&this.target)throw new Error('Multiple attributes declared, use either "target" or "text"');if(this.text)this.selectFake();else{if(!this.target)throw new Error('Missing required attributes, use either "target" or "text"');this.selectTarget()}},t.prototype.selectFake=function t(){var e=this;this.removeFake(),this.fakeHandler=document.body.addEventListener("click",function(){return e.removeFake()}),this.fakeElem=document.createElement("textarea"),this.fakeElem.style.position="absolute",this.fakeElem.style.left="-9999px",this.fakeElem.style.top=(window.pageYOffset||document.documentElement.scrollTop)+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=c.default(this.fakeElem),this.copyText()},t.prototype.removeFake=function t(){this.fakeHandler&&(document.body.removeEventListener("click"),this.fakeHandler=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)},t.prototype.selectTarget=function t(){this.selectedText=c.default(this.target),this.copyText()},t.prototype.copyText=function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(n){e=!1}this.handleResult(e)},t.prototype.handleResult=function t(e){e?this.emitter.emit("success",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)}):this.emitter.emit("error",{action:this.action,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})},t.prototype.clearSelection=function t(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()},t.prototype.destroy=function t(){this.removeFake()},i(t,[{key:"action",set:function t(){var e=arguments.length<=0||void 0===arguments[0]?"copy":arguments[0];if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!=typeof e||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');this._target=e}},get:function t(){return this._target}}]),t}();n.default=s,e.exports=n.default},{select:6}],9:[function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}n.__esModule=!0;var c=t("./clipboard-action"),s=r(c),u=t("tiny-emitter"),l=r(u),f=t("good-listener"),d=r(f),h=function(t){function e(n,r){o(this,e),t.call(this),this.resolveOptions(r),this.listenClick(n)}return i(e,t),e.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText},e.prototype.listenClick=function t(e){var n=this;this.listener=d.default(e,"click",function(t){return n.onClick(t)})},e.prototype.onClick=function t(e){this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new s.default({action:this.action(e.target),target:this.target(e.target),text:this.text(e.target),trigger:e.target,emitter:this})},e.prototype.defaultAction=function t(e){return a("action",e)},e.prototype.defaultTarget=function t(e){var n=a("target",e);return n?document.querySelector(n):void 0},e.prototype.defaultText=function t(e){return a("text",e)},e.prototype.destroy=function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)},e}(l.default);n.default=h,e.exports=n.default},{"./clipboard-action":8,"good-listener":5,"tiny-emitter":7}]},{},[9])(9)});
</script>
</body>
</html>
objIE.Document.all("loginview_textfield_username").innertext = Dc_Usuario
objIE.Document.all("loginview_passwordfield_password").innertext = Dc_Senha
objIE.Document.getElementsByTagName("loginview_textfield_username").innertext = Dc_Usuario
objIE.Document.getElementsByTagName("loginview_passwordfield_password").innertext = Dc_Senha
Nenhum dos 2 modos acima funciona para preencher o campo usuário e senha.
Sempre apresenta o mesmo erro descrito abaixo:
Erro em tempo de execução '-2147023179 (800706b5)':
Erro de automação
Interface desconhecida
Hoje meu código esta desta forma:
Sub LoginViaBrowser()
Dim Dc_Usuario As String
Dim Dc_Senha As String
Dim Dc_URL As String
Dim objIE As New InternetExplorer 'Referencie "Microsoft Internet Controls"
'Abre o IE
objIE.Visible = True
'Define os dados de acesso e link da página de login
Dc_Usuario = "xxxxx.xxxx"
Dc_Senha = "xxxxxx"
Dc_URL = "http://10.58.182.234:8081/dr_routingadmin_pu/"
'Navega até o link informado
objIE.Navigate2 Dc_URL
newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 5
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime
'(name) do elemento input do site que irá logar
objIE.Document.all("loginview_textfield_username").innertext = Dc_Usuario
objIE.Document.all("loginview_passwordfield_password").innertext = Dc_Senha
'(name) do formulário a ser submetido
objIE.Document.all("login").submit
End Sub
Podem me ajudar com este tipo de situação?
A página que quero acessar e inserir os dados para login, quando mando inspecionar objeto tenho o seguinte código.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=11;chrome=1" />
<title>Avaya Dynamic Routing</title>
<style type="text/css">html, body {height:100%;margin:0;}</style>
<link rel="shortcut icon" type="image/vnd.microsoft.icon" href="./VAADIN/themes/avaya/favicon.ico" />
<link rel="icon" type="image/vnd.microsoft.icon" href="./VAADIN/themes/avaya/favicon.ico" />
</head>
<body scroll="auto" class=" v-generated-body">
<div id="drroutingadminpu-1958229476" class=" v-app avaya">
<div class=" v-app-loading"></div>
<noscript>
You have to enable javascript in your browser to use an application built with Vaadin.
</noscript>
</div>
<script type="text/javascript" src="./VAADIN/vaadinPush.js"></script>
<script type="text/javascript" src="./VAADIN/vaadinBootstrap.js"></script>
<script type="text/javascript">//<![CDATA[
if (!window.vaadin) alert("Failed to load the bootstrap javascript: ./VAADIN/vaadinBootstrap.js");
vaadin.initApplication("drroutingadminpu-1958229476",{"heartbeatInterval":300,"versionInfo":{"vaadinVersion":"7.3.10"},"vaadinDir":"./VAADIN/","authErrMsg":{"message":"Take note of any unsaved data, and <u>click here<\/u> or press ESC to continue.","caption":"Authentication problem"},"widgetset":"com.avaya.ept.dr.AppWidgetSet","theme":"avaya","comErrMsg":{"message":"Take note of any unsaved data, and <u>click here<\/u> or press ESC to continue.","caption":"Communication problem"},"serviceUrl":".","standalone":true,"sessExpMsg":{"message":"Take note of any unsaved data, and <u>click here<\/u> or press ESC key to continue.","caption":"Session Expired"}});
//]]></script>
<script type="text/javascript">
function reCiF(i){var f = document.getElementById(i);if(f!=null){f.style.overflow='hidden';var val=f.value;f.value='';f.value=val;f.style.height='0px';f.style.height = (f.scrollHeight+1)+'px';} else {console.log('the field with id ['+i+'] was not found');}}
function adClR_s(id){var eventHandler = function(){reCiF(id);};var element=document.getElementById(id);element.onkeyup=eventHandler;}
function configureSegmTableMxN(rules, dims){var start = new Date().getTime();for(var i=1;i<=rules;i++){ addResizeListenerToRow(i,dims);}console.log('time taken to add all listeners '+(new Date().getTime()-start))}
function addResizeListenerToRow(rowNumber, dims){ for(var k=1;k<=dims;k++){ var id=rowNumber+'#'+k; adClR_s(id); }}
function resizeSegmTableMxN(rules,dims){var start = new Date().getTime();for(var i=1;i<=rules;i++){ for(var k=1;k<=dims;k++){ var id=i+'#'+k; reCiF(id); }}console.log('time taken to refresh all fields '+(new Date().getTime()-start))}
/*! Copyright © 2015 Zeno Rocha clipboard.js v1.5.2 https://zenorocha.github.io/clipboard.js Licensed MIT © Zeno Rocha */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,r){function o(a,c){if(!n[a]){if(!e[a]){var s="function"==typeof require&&require;if(!c&&s)return s(a,!0);if(i)return i(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var l=n[a]={exports:{}};e[a][0].call(l.exports,function(t){var n=e[a][1][t];return o(n?n:t)},l,l.exports,t,e,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(t,e,n){var r=t("matches-selector");e.exports=function(t,e,n){for(var o=n?t:t.parentNode;o&&o!==document;){if(r(o,e))return o;o=o.parentNode}}},{"matches-selector":2}],2:[function(t,e,n){function r(t,e){if(i)return i.call(t,e);for(var n=t.parentNode.querySelectorAll(e),r=0;r<n.length;++r)if(n[r]==t)return!0;return!1}var o=Element.prototype,i=o.matchesSelector||o.webkitMatchesSelector||o.mozMatchesSelector||o.msMatchesSelector||o.oMatchesSelector;e.exports=r},{}],3:[function(t,e,n){function r(t,e,n,r){var i=o.apply(this,arguments);return t.addEventListener(n,i),{destroy:function(){t.removeEventListener(n,i)}}}function o(t,e,n,r){return function(n){var o=i(n.target,e,!0);o&&(Object.defineProperty(n,"target",{value:o}),r.call(t,n))}}var i=t("closest");e.exports=r},{closest:1}],4:[function(t,e,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.function=function(t){var e=Object.prototype.toString.call(t);return"[object Function]"===e}},{}],5:[function(t,e,n){function r(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!c.string(e))throw new TypeError("Second argument must be a String");if(!c.function(n))throw new TypeError("Third argument must be a Function");if(c.node(t))return o(t,e,n);if(c.nodeList(t))return i(t,e,n);if(c.string(t))return a(t,e,n);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function o(t,e,n){return t.addEventListener(e,n),{destroy:function(){t.removeEventListener(e,n)}}}function i(t,e,n){return Array.prototype.forEach.call(t,function(t){t.addEventListener(e,n)}),{destroy:function(){Array.prototype.forEach.call(t,function(t){t.removeEventListener(e,n)})}}}function a(t,e,n){return s(document.body,t,e,n)}var c=t("./is"),s=t("delegate");e.exports=r},{"./is":4,delegate:3}],6:[function(t,e,n){function r(t){var e;if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName)t.select(),e=t.value;else{var n=window.getSelection(),r=document.createRange();r.selectNodeContents(t),n.removeAllRanges(),n.addRange(r),e=n.toString()}return e}e.exports=r},{}],7:[function(t,e,n){function r(){}r.prototype={on:function(t,e,n){var r=this.e||(this.e={});return(r[t]||(r[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){function r(){o.off(t,r),e.apply(n,arguments)}var o=this;return r._=e,this.on(t,r,n)},emit:function(t){var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),r=0,o=n.length;for(r;o>r;r++)n[r].fn.apply(n[r].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),r=n[t],o=[];if(r&&e)for(var i=0,a=r.length;a>i;i++)r.fn!==e&&r.fn._!==e&&o.push(r);return o.length?n[t]=o:delete n[t],this}},e.exports=r},{}],8:[function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}n.__esModule=!0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=t("select"),c=r(a),s=function(){function t(e){o(this,t),this.resolveOptions(e),this.initSelection()}return t.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action=e.action,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""},t.prototype.initSelection=function t(){if(this.text&&this.target)throw new Error('Multiple attributes declared, use either "target" or "text"');if(this.text)this.selectFake();else{if(!this.target)throw new Error('Missing required attributes, use either "target" or "text"');this.selectTarget()}},t.prototype.selectFake=function t(){var e=this;this.removeFake(),this.fakeHandler=document.body.addEventListener("click",function(){return e.removeFake()}),this.fakeElem=document.createElement("textarea"),this.fakeElem.style.position="absolute",this.fakeElem.style.left="-9999px",this.fakeElem.style.top=(window.pageYOffset||document.documentElement.scrollTop)+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=c.default(this.fakeElem),this.copyText()},t.prototype.removeFake=function t(){this.fakeHandler&&(document.body.removeEventListener("click"),this.fakeHandler=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)},t.prototype.selectTarget=function t(){this.selectedText=c.default(this.target),this.copyText()},t.prototype.copyText=function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(n){e=!1}this.handleResult(e)},t.prototype.handleResult=function t(e){e?this.emitter.emit("success",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)}):this.emitter.emit("error",{action:this.action,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})},t.prototype.clearSelection=function t(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()},t.prototype.destroy=function t(){this.removeFake()},i(t,[{key:"action",set:function t(){var e=arguments.length<=0||void 0===arguments[0]?"copy":arguments[0];if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!=typeof e||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');this._target=e}},get:function t(){return this._target}}]),t}();n.default=s,e.exports=n.default},{select:6}],9:[function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}n.__esModule=!0;var c=t("./clipboard-action"),s=r(c),u=t("tiny-emitter"),l=r(u),f=t("good-listener"),d=r(f),h=function(t){function e(n,r){o(this,e),t.call(this),this.resolveOptions(r),this.listenClick(n)}return i(e,t),e.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText},e.prototype.listenClick=function t(e){var n=this;this.listener=d.default(e,"click",function(t){return n.onClick(t)})},e.prototype.onClick=function t(e){this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new s.default({action:this.action(e.target),target:this.target(e.target),text:this.text(e.target),trigger:e.target,emitter:this})},e.prototype.defaultAction=function t(e){return a("action",e)},e.prototype.defaultTarget=function t(e){var n=a("target",e);return n?document.querySelector(n):void 0},e.prototype.defaultText=function t(e){return a("text",e)},e.prototype.destroy=function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)},e}(l.default);n.default=h,e.exports=n.default},{"./clipboard-action":8,"good-listener":5,"tiny-emitter":7}]},{},[9])(9)});
</script>
</body>
</html>
- Mikel Silveira Fraga
- Jedi
- Mensagens: 1173
- Registrado em: Sex Mai 27, 2011 3:27 pm
- Localização: Governador Valadares - MG
- Contato:
Re: Interação VBA com Internet Explorer (dúvidas)
Palermo, boa noite.
Cara, nesse código da página que você enviou, não consegui encontrar nenhuma referência para as expressões "loginview_textfield_username" e "loginview_passwordfield_password".
Uma coisa que vou adiantar é que para utilizar o comando objIE.Document.getElementsByTagName(), a referencia utilizada precisa ser os elementos Html como: Td, Tr, Ul, Ol, Table, p, Div, etc.
Agora, quando esta utilizando o comando objIE.Document.all(), é pego o Id do elemento. Nesse caso, é preciso verificar se essas duas referências acima são do atributo Id ou Name do Elemento Html.
Veja esses pontos e nos retorne.
Abraços e boa noite.
Cara, nesse código da página que você enviou, não consegui encontrar nenhuma referência para as expressões "loginview_textfield_username" e "loginview_passwordfield_password".
Uma coisa que vou adiantar é que para utilizar o comando objIE.Document.getElementsByTagName(), a referencia utilizada precisa ser os elementos Html como: Td, Tr, Ul, Ol, Table, p, Div, etc.
Agora, quando esta utilizando o comando objIE.Document.all(), é pego o Id do elemento. Nesse caso, é preciso verificar se essas duas referências acima são do atributo Id ou Name do Elemento Html.
Veja esses pontos e nos retorne.
Abraços e boa noite.
Re: Interação VBA com Internet Explorer (dúvidas)
Opa, Obrigado Mikel por retornar minha duvida.
Pesquisando os campos na janela do IE na parte de Inspecionar Elemento encontro as seguintes informações:
Campo Username:
<td class="vformlayout-contentcell">
<input tabindex="0" class="v-textfield v-widget v-has-width" id="loginview_textfield_username" aria-labelledby="gwt-uid-4" style="width: 15em;" type="text">
</td>
Campo Senha:
<td class="vformlayout-contentcell">
<input tabindex="0" class="v-textfield v-widget v-has-width" id="loginview_passwordfield_password" aria-labelledby="gwt-uid-6" style="width: 15em;" type="password">
</td>
Maldito Botão de Logar que também não consigo acionar através do Click no vba:
<div class="v-csslayout v-layout v-widget buttons v-csslayout-buttons"><div tabindex="0" class="v-button v-widget danger v-button-danger" id="loginview_button_login" role="button"><span class="v-button-wrap"><span class="v-button-caption">Login</span></span></div></div>
meu código VBA esta assim, dei uma evoluída pesquisando mais na internet, mas to travado pois ainda não consigo logar.
Sub LogarAvaya()
Dim IE As InternetExplorerMedium 'Este objeto (a variedade "médio" em oposição a "InternetExplorer") é necessário no nosso nivel de segurança
Dim targetURL As String
Dim webContent As String
Dim sh
Dim eachIE
targetURL = "http://10.58.182.234:8081/dr_routingadmin_pu/"
Set IE = New InternetExplorerMedium
IE.Visible = True 'Define como true para ver o que está acontecendo
IE.navigate targetURL
While IE.Busy
DoEvents
Wend
Do
Set sh = New Shell32.Shell
For Each eachIE In sh.Windows
If InStr(1, eachIE.LocationURL, targetURL) Then
Set IE = eachIE
'IE.Visible = False 'Alterar aqui, pois em alguns ambientes , novos padrões de processo para visível.
Exit Do
End If
Next eachIE
Loop
Set eachIE = Nothing
Set sh = Nothing
While IE.Busy 'O novo processo ainda pode estar ocupado , mesmo depois de encontrá-lo
DoEvents
Wend
Set campo = IE.document.all("loginview_textfield_username")
campo.Value = "xxxx.xxxx"
Set campo = IE.document.all("loginview_passwordfield_password")
campo.Value = "xxxxxx"
Set estimate = IE.document.getElementById("loginview_button_login")
campo.Click
'Set campo = IE.Document.all("loginview_button_login")
'campo.Click
'IE.Document.all("loginview_textfield_username").Value = Dc_Usuario 'essa bagaça ai é espiritual, sinistra
'IE.Document.all("loginview_passwordfield_password").Value = Dc_Senha
'(name) do formulário a ser submetido
'IE.Document.all("login").submit
End Sub
Anexei a planilha com a macro e o código para que possa analisar melhor, derrepente é mais útil assim!
Pesquisando os campos na janela do IE na parte de Inspecionar Elemento encontro as seguintes informações:
Campo Username:
<td class="vformlayout-contentcell">
<input tabindex="0" class="v-textfield v-widget v-has-width" id="loginview_textfield_username" aria-labelledby="gwt-uid-4" style="width: 15em;" type="text">
</td>
Campo Senha:
<td class="vformlayout-contentcell">
<input tabindex="0" class="v-textfield v-widget v-has-width" id="loginview_passwordfield_password" aria-labelledby="gwt-uid-6" style="width: 15em;" type="password">
</td>
Maldito Botão de Logar que também não consigo acionar através do Click no vba:
<div class="v-csslayout v-layout v-widget buttons v-csslayout-buttons"><div tabindex="0" class="v-button v-widget danger v-button-danger" id="loginview_button_login" role="button"><span class="v-button-wrap"><span class="v-button-caption">Login</span></span></div></div>
meu código VBA esta assim, dei uma evoluída pesquisando mais na internet, mas to travado pois ainda não consigo logar.
Sub LogarAvaya()
Dim IE As InternetExplorerMedium 'Este objeto (a variedade "médio" em oposição a "InternetExplorer") é necessário no nosso nivel de segurança
Dim targetURL As String
Dim webContent As String
Dim sh
Dim eachIE
targetURL = "http://10.58.182.234:8081/dr_routingadmin_pu/"
Set IE = New InternetExplorerMedium
IE.Visible = True 'Define como true para ver o que está acontecendo
IE.navigate targetURL
While IE.Busy
DoEvents
Wend
Do
Set sh = New Shell32.Shell
For Each eachIE In sh.Windows
If InStr(1, eachIE.LocationURL, targetURL) Then
Set IE = eachIE
'IE.Visible = False 'Alterar aqui, pois em alguns ambientes , novos padrões de processo para visível.
Exit Do
End If
Next eachIE
Loop
Set eachIE = Nothing
Set sh = Nothing
While IE.Busy 'O novo processo ainda pode estar ocupado , mesmo depois de encontrá-lo
DoEvents
Wend
Set campo = IE.document.all("loginview_textfield_username")
campo.Value = "xxxx.xxxx"
Set campo = IE.document.all("loginview_passwordfield_password")
campo.Value = "xxxxxx"
Set estimate = IE.document.getElementById("loginview_button_login")
campo.Click
'Set campo = IE.Document.all("loginview_button_login")
'campo.Click
'IE.Document.all("loginview_textfield_username").Value = Dc_Usuario 'essa bagaça ai é espiritual, sinistra
'IE.Document.all("loginview_passwordfield_password").Value = Dc_Senha
'(name) do formulário a ser submetido
'IE.Document.all("login").submit
End Sub
Anexei a planilha com a macro e o código para que possa analisar melhor, derrepente é mais útil assim!
- Anexos
-
- Avaya(Login Automatico) - Copia.zip
- (15.94 KiB) Baixado 623 vezes
- Mikel Silveira Fraga
- Jedi
- Mensagens: 1173
- Registrado em: Sex Mai 27, 2011 3:27 pm
- Localização: Governador Valadares - MG
- Contato:
Re: Interação VBA com Internet Explorer (dúvidas)
Palermo, boa tarde.
Dei uma olhada no seu código e percebi que você chegou a utilizar o comando getElementById, como havia mencionado.
Percebi também que todas as referências são para o atributo Id do Elemento Html. Se mesmo assim não esta funcionando, eu suspeito que esse site/sistema que esta tentando acessar utiliza o recurso de iFrames ou algo parecido com Php.
Nesse caso, fica difícil dar qualquer tipo de ajuda, pois o endereço que você esta acessando me parece ser um endereço interno, provavelmente um sistema que roda apenas na rede em que você tem acesso. Não tenho como testar seu código e verificar o que realmente esta ocorrendo.
Nesse caso, pegue os códigos abaixo e tente utilizá-los:
- Caixa de Texto Usuário e Senha:
- Botão para Login:
Espero que você consiga evoluir com esses códigos.
Abraços e excelente final de semana.
Dei uma olhada no seu código e percebi que você chegou a utilizar o comando getElementById, como havia mencionado.
Percebi também que todas as referências são para o atributo Id do Elemento Html. Se mesmo assim não esta funcionando, eu suspeito que esse site/sistema que esta tentando acessar utiliza o recurso de iFrames ou algo parecido com Php.
Nesse caso, fica difícil dar qualquer tipo de ajuda, pois o endereço que você esta acessando me parece ser um endereço interno, provavelmente um sistema que roda apenas na rede em que você tem acesso. Não tenho como testar seu código e verificar o que realmente esta ocorrendo.
Nesse caso, pegue os códigos abaixo e tente utilizá-los:
- Caixa de Texto Usuário e Senha:
Código: Selecionar todos
Dim oElement As Object
Dim oElementCol As Object
Set oElementCol = IE.Document.getElementsByTagName("input")
For Each oElement in oElementCol
If oElement.Id = "loginview_textfield_username" Then
oElement.innerText = "Usuário"
ElseIf oElement.Id = "loginview_passwordfield_password" Then
oElement.innerText = "Senha"
End If
Next oElement
Código: Selecionar todos
Dim oElement As Object
Dim oElementCol As Object
Set oElementCol = IE.Document.getElementsByTagName("div")
For Each oElement in oElementCol
If oElement.Id = "loginview_button_login" Then
oElement.Click
End If
Next oElement
Abraços e excelente final de semana.
Re: Interação VBA com Internet Explorer (dúvidas)
Mikel, Obrigado novamente pela ajuda!
Realmente este site é interno, ambiente empresa!
Estou tentando ja faz uns 3 dias, mas não estou conseguindo mesmo!
A coisa esta feia. kkkkk
Notei que o site deve ter realmente alguma proteção, mas ele trabalha sim com iframes.
Realmente este site é interno, ambiente empresa!
Estou tentando ja faz uns 3 dias, mas não estou conseguindo mesmo!
A coisa esta feia. kkkkk
Notei que o site deve ter realmente alguma proteção, mas ele trabalha sim com iframes.
Re: Interação VBA com Internet Explorer (dúvidas)
Como fazer para meu código de vba informar se uma determinada expressão em uma página html está colorida ou não?
Por exemplo: Se cor do "td" for red então escreva "red", senão "".
Por exemplo: Se cor do "td" for red então escreva "red", senão "".
- Mikel Silveira Fraga
- Jedi
- Mensagens: 1173
- Registrado em: Sex Mai 27, 2011 3:27 pm
- Localização: Governador Valadares - MG
- Contato:
Re: Interação VBA com Internet Explorer (dúvidas)
NSN, bom dia.
Que tipo de biblioteca você esta utilizando: Microsoft Internet Control ou Selenium VBA?
Já vou lhe adiantando que nunca vi esse tipo de solicitação, mas podemos dar uma olhada se você disponibilizar um modelo do que tem e o link de onde você esta tentando validar essa informação. Desta forma, podemos testar o código.
Aguardo retorno.
Que tipo de biblioteca você esta utilizando: Microsoft Internet Control ou Selenium VBA?
Já vou lhe adiantando que nunca vi esse tipo de solicitação, mas podemos dar uma olhada se você disponibilizar um modelo do que tem e o link de onde você esta tentando validar essa informação. Desta forma, podemos testar o código.
Aguardo retorno.
Re: Interação VBA com Internet Explorer (dúvidas)
Remover... por favor
Editado pela última vez por belletti em Ter Jan 17, 2017 9:28 am, em um total de 1 vez.
Re: Interação VBA com Internet Explorer (dúvidas)
Galera, sou novato no ramo de VBA e estou com o seguinte problema:
Navego pelo site da empresa inserindo filtros para extração de relatórios em .xls... porém, estou encontrando um problema no momento de fazer o download da planilha.
A macro está inserindo os filtros (data, segmento de serviço e etc.) e clicando no botão para filtrar a base perfeitamente.
Neste momento, abre uma janela por cima da página (acredito que como uma DIV) e o "Botão" com a img do excel que é um TD que não possui ID nem Name...
No caso, eu preciso ativar o onClick="imprimeRelatorioExcel('excel')" que é uma function no inicio do codigo.
eu percebi que quando vou apertando a tecla Tab nessa DIV que abre, o que é selecionado são os filtros de datas e serviços da página anterior, sendo que na página de download só tem 2 "botões" que é para imprimir ou exportar em formato EXCEL.
Desculpem se não fui claro, espero que os Deuses do VBA me deêm uma luz ! HAHAHA
Abraço e obrigado desde já !
Navego pelo site da empresa inserindo filtros para extração de relatórios em .xls... porém, estou encontrando um problema no momento de fazer o download da planilha.
A macro está inserindo os filtros (data, segmento de serviço e etc.) e clicando no botão para filtrar a base perfeitamente.
Neste momento, abre uma janela por cima da página (acredito que como uma DIV) e o "Botão" com a img do excel que é um TD que não possui ID nem Name...
Código: Selecionar todos
Codigo do site:
<table align="center">
<tr>
<td nowrap onmouseover="style.cursor='pointer';style.cursor='hand'" title="Clique para Exportar o Relatório para o Excel" onClick="imprimeRelatorioExcel('excel')">
<center><img src="imagens/excel.gif" align="bottom" ><font class="txt5"><b> </center>
</td>
<td nowrap onmouseover="style.cursor='pointer';style.cursor='hand'" title="Clique para Imprimir" onClick="imprimeRelatorioExcel('imprimir')">
<center><img src="imagens/print1.gif" width="25" align="bottom" ><font class="txt5"><b> </center>
</td>
</tr>
</table>
No caso, eu preciso ativar o onClick="imprimeRelatorioExcel('excel')" que é uma function no inicio do codigo.
eu percebi que quando vou apertando a tecla Tab nessa DIV que abre, o que é selecionado são os filtros de datas e serviços da página anterior, sendo que na página de download só tem 2 "botões" que é para imprimir ou exportar em formato EXCEL.
Desculpem se não fui claro, espero que os Deuses do VBA me deêm uma luz ! HAHAHA
Abraço e obrigado desde já !