Ir para conteúdo
Fórum Script Brasil
  • 0

VBA interagindo com IE


CANIL

Pergunta

Tenho sempre entrado nesse forum para tirar duvidas do VBA com o IE. So que não consegui matar 2 duvidas.

Tenho uma macro que loga no meu email pessoal e envia um email para o meu email do trabalho, porem, gostaria de saber como posso anexar um arquivo nesse email, visto que, quando foi anexar um arquivo ele sai da tela do IE e abre outra janela, o que quero saber é como posso controlar essa janela. A outra duvida e meio que relacionada a essa, gostaria de saber como faco para controla uma janela já aberta do windows (IE mesmo) sem ter que criar um novo objeto. Pois a pouco fiz uma macro mt parecida so que nela quando clicava num link ela abrir outra janela isso me atrabalha um pouco. Fico grato se alguém me ajudar.

Sou novo no forum e se caso eu estiver comentendo algum erro ao abrir um tópico, gostaria de orientacao.

Obrigado...

Link para o comentário
Compartilhar em outros sites

5 respostass a esta questão

Posts Recomendados

  • 0

Bem já descobrir a parte de busca a janela tenho o codigo sendo que agora falta uma comando em VBA para selecionar o item ou colocar o nome dele no camdo nome do arquivo que fica na tela de anexar aruqivo... a mesma tela q usamos para abrir arquivo no Excel... alguém sabe como fazer isso...

Se alguema quiser o codigo eu posso esta postando aki...

Abracos.

Link para o comentário
Compartilhar em outros sites

  • 0

Posta o código.

Mas já te adianto de que você vai precisar usar duas APIs do Windows para fazer isso: SendMessage e GetWindow.

Vai estudando estas APIs enquanto eu tento achar uma solução também com base nestas APIs

Link para o comentário
Compartilhar em outros sites

  • 0
Posta o código.

Mas já te adianto de que você vai precisar usar duas APIs do Windows para fazer isso: SendMessage e GetWindow.

Vai estudando estas APIs enquanto eu tento achar uma solução também com base nestas APIs

Estive lendo sobre elas... No meu odigo já tem até elas. Estive lendo tambem sobre o BW_Click... acho q é BW mesmo.

Bem o mais logico que achei foi tentar enviar uma sendmessage de click para a tela mas ainda não conseguir entender como funcionar esse comando muito bem, se poder me ajudar. vou deixar o codigo com estar agora, vai ter algumas alteraceos porem já da pra ter uma ideia.

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Const SW_SHOWNORMAL = 1
Const WM_CLOSE = &H10
Const gcClassnameMSWord = "OpusApp"
Const gcClassnameMSExcel = "XLMAIN"
Const gcClassnameMSIExplorer = "IEFrame"
Const gcClassnameMSVBasic = "wndclass_desked_gsk"
Const gcClassnameNotePad = "Notepad"
Const gcClassnameMyVBApp = "ThunderForm"

Sub Mandar_email()

'Macro feita para configrar busca valores.
'Criado por Victor Almada de Hollanda.
'Contato victorah@globo.com ou 93850315

Dim lHandle As Long
Dim appIE As InternetExplorer
Dim UserN As Variant, PW As Variant
Dim Element As HTMLButtonElement
Dim btnInput As MSHTML.HTMLInputElement
Dim ElementCol As MSHTML.IHTMLElementCollection
Dim Link As MSHTML.HTMLAnchorElement
Dim strCountBody As String
Dim TextIWant As String
Dim oHTML1 As IHTMLElement
'variaveis constantes.
test1 = 0
linha2 = 0
Linha = 2
Pref1 = "https://login.globo.com/login/1"
    
    
    Set oWeb = CreateObject("InternetExplorer.Application")
    oWeb.navigate Pref1
    'oWeb.FullScreen = True
    oWeb.Visible = True
    Do Until oWeb.readyState = READYSTATE_COMPLETE
    Loop
        
        
        'Comando para pagina de erro de certificado
        Set oHTML = oWeb.document
        cont1 = 0
        b = "O Internet Explorer não pode exibir a página da Web"
        c = "Navegação Cancelada"
        d = "404 Not Found "
        For Each oHTML1 In oHTML.all
        
            If oHTML1.innerText = b Or oHTML1.innerText = c Then
                
                oWeb.Application.Quit
                Linha = Linha + 1
                MsgBox ("Erro na pagina")
                'GoTo Fim
            
            
            ElseIf oHTML1.innerText = d Then
                
                oWeb.Application.Quit
                Linha = Linha + 1
                MsgBox ("Fora do AR")
                'GoTo Fim
            
            End If
                
            If cont1 = 3 Then
                
                Exit For
            
            End If
            
            cont1 = cont1 + 1
            
        Next
        'fim do codigo para o erro de certificado. O codigo acima eu peguei de uma outra macro q fiz q tinha erro de certificado, porem, serve para caso a internet esteja fora.

    
        'Metodo de login no site.
        oWeb.document.all("login-passaporte").innerText = "nomedoemail"        'Login
        oWeb.document.all("senha-passaporte").innerText = "senha"              'Senha
        
        'Aqui entro no meu email.
        Set ElementCol = oWeb.document.getElementsByTagName("INPUT")
            
            For Each btnInput In ElementCol
                
                If btnInput.Name = "botaoacessar" Then
                    
                    btnInput.Click
                    
                    Exit For
                
                End If
            
        Next btnInput
        Do While oWeb.Busy
        DoEvents
        Loop
        Do Until oWeb.readyState = READYSTATE_COMPLETE
        Loop
        
        Set ElementCol = oWeb.document.getElementsByTagName("a")
            
            For Each Link In ElementCol
                
                If Link.innerHTML = "Escrever e-mail" Then
                    
                    Link.Click
                    Exit For
                    
                End If
                
        Next Link
        Do Until oWeb.readyState = READYSTATE_COMPLETE
        Loop
        
        'Aparti daqui fecho a entra do meu email e selecao de escrever mensagem.
        Set ElementCol = oWeb.document.getElementsByTagName("INPUT")
            
            For Each btnInput In ElementCol
                
                If btnInput.Name = "file0" Then
11:
                    btnInput.Click  'Aqui ele dentro do meu email ele clica em Anexar(o ideal era adicionar o caminho mas n tem no codigo HTML)
                    
                    'Esse codigo serve pra buscar a jane de anexar arquivo, aprincipio ela não tem mt serventia porem depois vou pescisar disso.
                    Dim WinWnd As Long, Ret As String, RetVal As Long, lpClassName As String
                    Ret = InputBox("Enter the exact window title:" + Chr$(13) + Chr$(10) + "Note: must be an exact match")
                    WinWnd = FindWindow(vbNullString, Ret)
                    If WinWnd = 0 Then MsgBox "Couldn't find the window ...": Exit Sub
                    ShowWindow WinWnd, SW_SHOWNORMAL
                    lpClassName = Space(256)
                    RetVal = GetClassName(WinWnd, lpClassName, 256)
                    MsgBox "Classname: " + Left$(lpClassName, RetVal)
                    'esse codigo so busca a chanela, mas queria tambem acrecentar nele uma forma de busca o arquivo,
                    'que tem dentro dessa janela(janela de anexar arquivo). O que quero mesmo seria colocar o "Nome do arquivo"
                    'ou selecionar o arquivo e clicar em abrir.
                    'pra baixo ainda tem mas codigo mas so poderei adcionar depois que terminar essa parte.
                    
                    
                    GoTo 11
                    Exit For
                    
                End If
                
        Next btnInput
        Do While oWeb.Busy
        DoEvents
        Loop
        
End Sub

Valeu ai plea forca...

Link para o comentário
Compartilhar em outros sites

  • 0

Boas notícias, achei a solução, ou melhor, as duas soluções.

1) "A outra duvida e meio que relacionada a essa, gostaria de saber como faco para controla uma janela já aberta do windows (IE mesmo) sem ter que criar um novo objeto".

Sim, vide código abaixo:

Function GetOpenIEByURL()

    'Adicionar referência ao 'Microsoft Internet Controls'
   
    Dim ie As InternetExplorer
    Dim objShellWindows As New SHDocVw.ShellWindows
   
    i_URL = "http://www.google.com.br/"
   
    On Error Resume Next
   
    For Each ie In objShellWindows
   
        If TypeName(ie.Document) = "HTMLDocument" Then
       
            If ie.Document.URL = i_URL Then
           
            ie.Document.all.Item("q").innerText = "Teste"
           
            End If
           
        End If
       
    Next

End Function
Esse cara aqui SHDocVw.ShellWindows permite você percorrer todas as instâncias de Internet Explorer abertas em sua máquina e fazer um loop usando o objeto InternetExplorer. 2) "Tenho uma macro que loga no meu email pessoal e envia um email para o meu email do trabalho, porem, gostaria de saber como posso anexar um arquivo nesse email, visto que, quando foi anexar um arquivo ele sai da tela do IE e abre outra janela, o que quero saber é como posso controlar essa janela." Eu entendi que você esteja falando daquela janela do Windows "Selecionar arquivo", certo? Use o código abaixo. Só um ponto de atenção é mudar o nome da janela e do botão "Abrir" no código, pois eu fiz no Windows em Inglês, ok?
Private Declare Function GetWindow Lib "user32" (ByVal hWnd _
    As Long, ByVal wFlag As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias _
    "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As _
    String, ByVal cch As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias _
    "FindWindowA" (ByVal lpClassName As String, ByVal _
    lpWindowName As String) As Long
Private Declare Function GetClassName Lib "user32" Alias _
    "GetClassNameA" (ByVal hWnd As Long, ByVal _
    lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias _
    "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal _
    wParam As Long, lParam As Any) As Long
Private Declare Function PostMessage Lib "user32" Alias _
"PostMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, lParam As Any) As Long


Const WM_CLOSE = &H10
Const WM_SETTEXT = &HC
Const WM_SYSKEYDOWN = &H104
Const WM_RBUTTONDOWN = &H204
Const WS_MAXIMIZE = &H1000000
Const WM_CHAR = &H102
Const BM_CLICK As Long = &HF5&

Private Const GW_HWNDNEXT = 2&
Private Const GW_CHILD = 5&


Private Function GetFirstTextBoxHandle(nFormCaption As String, _
    pClass As String, Optional nTextboxText As String) As Long

    Dim iHwnd As Long
    Dim iSize As Long
    Dim iClass As String
    Dim iText As String

    iHwnd = FindWindow(vbNullString, nFormCaption)
    If iHwnd Then
        iHwnd = GetWindow(iHwnd, GW_CHILD)
        Do While iHwnd
            iClass = Space(64)
            iSize = GetClassName(iHwnd, iClass, Len(iClass))
            If iSize > 0 Then
                iClass = Left(iClass, iSize)
               
                'If iClass = "ThunderTextBox" Or iClass = "ComboBoxEx32" Then
                'Debug.Print iClass
               
                If iClass = pClass Then
                    If nTextboxText <> "" Then
                        iText = Space(100)
                        GetWindowText iHwnd, iText, 100&
                        iText = Left(iText, InStr(iText, _
                            Chr(0)) - 1)
                            'Debug.Print iText
                        If iText = nTextboxText Then
                            GetFirstTextBoxHandle = iHwnd
                            Exit Function
                        End If
                    Else
                        GetFirstTextBoxHandle = iHwnd
                        Exit Function
                    End If
                End If
            End If
            iHwnd = GetWindow(iHwnd, GW_HWNDNEXT)
        Loop
    End If
End Function

Private Sub Command1_Click()
    Dim WINDOWCAPTION As String
    WINDOWCAPTION = "Choose file"
   
    SendMessage GetFirstTextBoxHandle(WINDOWCAPTION, "ComboBoxEx32"), WM_SETTEXT, ByVal 0, ByVal "Aqui vai o nome do anexo e endereço"
    PostMessage GetFirstTextBoxHandle(WINDOWCAPTION, "Button", "&Open"), BM_CLICK, 0, 0
   
End Sub
Se teu Windows não for em inglês você vai ter que mudar o valor da variável WINDOWCAPTION para o nome que aparece na janela de selecionar arquivo e o nome do botão "Abrir" (está como "&Open") na linha de código abaixo:
PostMessage GetFirstTextBoxHandle(WINDOWCAPTION, "Button", "&Open"), BM_CLICK, 0, 0

Espero ter ajudado (espero mesmo, porque deu um trabalho achar isso)... mas replicar conhecimento nunca é demais.

Abraços

Editado por João.Neto
Link para o comentário
Compartilhar em outros sites

  • 0
Prezados,

Estou com uma planilha, cujo nela estou implementando um script, que vai monitorar o nível de toner de cada impressora. sendo que cada impressora consigo acessa via web atraves de um IP.

Com esse script vou poder monitorar as 20 impressoras no qual sou responsável.

Conforme a planilha em anexo os dados serão exibidos pelo Range F4 a F24.

Abaixo segue o script que esta sendo criado, mas esta compilando com erros.

-----------------------------------
Erro de compilação
-----------------------------------
Link:http://1drv.ms/1MEWLIM
------------------------------------------------------

Option Explicit
Public Sub spuRetornarStatusToner()

Dim wbk As Excel.Workbook
Set wbk = Excel.ThisWorkbook

Dim wsh As Excel.Worksheet
Set wsh = wbk.Sheets("CONTROLE")

Dim nvgInternetExplorer As InternetExplorer
Dim objIeDoc As Object
Dim htmLinha As HTMLTableRow
Dim htmColuna As HTMLTableCol

Dim i As Integer

For i = 1 To 20

Set nvgInternetExplorer = New InternetExplorerMedium
nvgInternetExplorer.Navigate ("http://10.10.10.10")
nvgInternetExplorer.Visible = True

While nvgInternetExplorer.ReadyState <> 4
Wend

Set objIeDoc = nvgInternetExplorer.Document

For Each htmLinha In objIeDoc.all.tags("tr")
For Each htmColuna In htmLinha.all.tags("td")
If Left$(htmColuna.innerText, 16) = "Cartucho Preto ~" Then
MsgBox Right$(htmColuna.innerText, Len(htmColuna.innerText) - 16) ' para teste verificando se o valor está correto
wsh.Range("F" & 3 + i).Value = Right$(htmColuna.innerText, Len(htmColuna.innerText) - 16)
End If
Next htmColuna
Next htmLinha

nvgInternetExplorer.Quit

Next i

Set nvgInternetExplorer = Nothing
Set objIeDoc = Nothing
Close

End Sub

--------------------------------------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------
Codigo fonte da paginar da web da impressora
-------------------------------------------------------

<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<meta HTTP-EQUIV="refresh" CONTENT="120; url=/cgi-bin/dynamic/printer/PrinterStatus.html">
<title>Printer Status</title>
<base target="_self">
<LINK REL="stylesheet" HREF="/cgi-bin/dynamic/printer/configStyle.css" TYPE="text/css">
</head>
<body>
<!-- Device Status Title-->

<h3>Status do dispositivo - <a href="/" TARGET="_top"><sub><b>Atualizar</b></sub></a></h3>




<!-- Job Parking -->


<hr class="status_hr"/>

<!-- Panel and Toner Level -->
<table class="status_table">
<tr>
<th colspan="4">&nbsp;</th>
</tr>



<!-- Toner Level -->

<tr>
<td colspan="4">
<B>Status do toner:</B>
</td>
</tr>


<TR><TD COLSPAN=4><B>Cartucho Preto ~100%</B></TD></TR><TR>
<TD width="25%">
<TABLE style="table-layout:fixed" borderColor=#000000 cellSpacing=0 width="100%" border=1><TBODY>
<TR>
<TD width="100%" bgColor=#000000>&nbsp;</TD><TD width="0%" bgColor=#ffffff>&nbsp;</TD></TR></TBODY></TABLE></TD><TD COLSPAN=3>&nbsp;</TD></TR> 

</table>

<hr class="status_hr">
<table class="status_table">
<tr>
<th colspan="5">&nbsp;</th>
</tr>

<tr>
<td width="23%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Bandeja de entrada de papel:</B></P> </TD>
<td width="20%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Status:</B></P> </TD>
<td width="15%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Capacidade:</B></P></TD>
<td width="15%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Tamanho:</B></P></TD>
<td width="25%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Tipo:</B></TD>
</tr>

<TR>
<TD><P style="margin-left:5">Bandeja 1</P></TD>
<td width="30%"><P style="margin-left:5"><table width="50%" bgcolor="#009900" style="padding: .75pt" height="1"><tr><td><b>OK</b></TD></TR></TABLE></P></TD>
<TD><P style="margin-left:5">550</P></TD>
<TD><P style="margin-left:5">A4</P></TD>
<TD><P style="margin-left:5">Papel&nbsp;comum</P></TD>
</TR>
<TR>
<TD><P style="margin-left:5">Alimentador MF</P></TD>
<td width="30%"><P style="margin-left:5"><table width="50%" bgcolor="FFFFFF" style="padding: .75pt" height="1"><tr><td><b>OK</b></TD></TR></TABLE></P></TD>
<TD><P style="margin-left:5">100</P></TD>
<TD><P style="margin-left:5">A4</P></TD>
<TD><P style="margin-left:5">Tipo&nbsp;personalizado&nbsp;6</P></TD>
</TR>



</table>

<hr class="status_hr"/>

<table class="status_table">

<tr>
<td width="23%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Bandeja de saída de papel:</B></P></TD>
<td width="20%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Status:</B></P> </TD>
<td width="15%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B>Capacidade:</B></P></TD>
<td width="15%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B></B></P></TD>
<td width="25%"><P align="left" style="margin-top: 5; margin-bottom: 5"><B></B></P></TD>
</tr>
<TR>
<TD><P style="margin-left:5">Bandeja padrão</P></TD>
<td width="30%"><P style="margin-left:5"><table width="50%" bgcolor="#009900" style="padding: .75pt" height="1"><tr><td><b>OK</b></TD></TR></TABLE></P></TD>
<TD><P style="margin-left:5">250</P></TD>
<TD><P style="margin-left:5"></P></TD>
<TD><P style="margin-left:5"></P></TD>
</TR>

</table>

<hr class="status_hr">
<table class="status_table">
<tr>
<th colspan="2">&nbsp;</th>
</tr>
<TR>
<TD width="40%"><B>Tipo de dispositivo:</B></TD><TD width="60%">Laser monocromática</TD>
</TR><TR>
<TD><B>Velocidade:</B></TD><TD>Até 50 Páginas/minuto</TD>
</TR><TR>
<TD><B>Cartucho toner Capacidade:</B></TD><TD>Aproximadamente 7.500 páginas com 5% de cobertura</TD>
</TR><TR>
<TD><B>Kit manutenção Vida restante:</B></TD><TD>100%</TD>
</TR><TR>
<TD><B>Unid. imagem Vida restante:</B></TD><TD>87%</TD>
</TR>
</table>



</body>
</html>

----------------------------------------------------------------------------------------------------------------------------------------------------
 
Voces podem me ajudar?

SCRIPT2.JPG

SCRIPT.JPG

SCRIPT1.JPG

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...