Página 1 de 2

[RESOLVIDO] AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Seg Dez 03, 2018 10:24 pm
por Wagner.cwb
Olá Nobres!

estou com um código que me atende perfeitamente quando realizo o debug manualmente (linha a linha - F8), porém quando mando executar via "botão" ou "play" ocorre sempre o mesmo erro (Erro Exceção de HRESULT: 0x800A03EC) na linha "tabela.AsTable.ToExcel Destino", então mando depurar e aperto F8 e o mesmo avança sem acusar erro... isso que eu acho estranho, pois avança sem precisar tratar nada. Por favor, podem me ajudar?

Código na integra:

Código: Selecionar todos

ub extrairTabelasWeb()

'FALTA TRATAR UNIDADES DE MEDIDAS PARA KM/H

Set driver = New ChromeDriver
driver.AddArgument ("--headless")
Dim iLnhCidade As Integer
Dim URL_Cidade As String
Dim NomeCidade As String


iLnhCidade = 2

'verificar qual cidade para coleta
While Worksheets("Alerta_Temporal").Range("CM" & iLnhCidade) <> ""

'grava url da cidade
URL_Cidade = Worksheets("Alerta_Temporal").Range("CQ" & iLnhCidade)
'grava nome da cidade
NomeCidade = Worksheets("Alerta_Temporal").Range("CM" & iLnhCidade)

'definir local para gravar dados coletados

Dim Destino As Range

'identifica ultima linha com valores

Worksheets("Alerta_Temporal").Activate
Worksheets("Alerta_Temporal").Range("B1048576").Activate
Selection.End(xlUp).Activate

'verifica se é o primeiro valor a receber
If ActiveCell.Offset(0, 0).Value <> "" Then
'se houver valores, pula 2 linhas abaixo
    ActiveCell.Offset(2, 0).Activate
    cabecalho = "nao"

End If

'define local para receber valores
Set Destino = ActiveCell.Offset(0, 0).Range("A1")

'carrega site da cidade
driver.get URL_Cidade

Dim tabela As WebElement
'localiza tabela de interesse
Set tabela = driver.FindElementById("detail-data-table")

If tabela Is Nothing Then

MsgBox "Elemento não encontrado"
Else
    'On Error GoTo Trata_Erro não sei como pular o erro, tentativa
    tabela.AsTable.ToExcel Destino 'AQUI OCORRE O ERRO - Erro Exceção de HRESULT: 0x800A03EC
    
    'tratamento layout
    If cabecalho = "nao" Then
    Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(2, 43)).Select
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlUp
    ActiveCell.Select
    End If
    
End If

    'tratamento layout
If cabecalho = "nao" Then
ActiveCell.Offset(0, -1) = NomeCidade
ActiveCell.Offset(1, -1) = "Chuva mm"
ActiveCell.Offset(2, -1) = "Vento km/h"
ActiveCell.Offset(3, -1) = "Rajadas km"
ActiveCell.Offset(4, -1) = "Direcao"

Else
ActiveCell.Offset(0, -1) = NomeCidade
End If

'busca nova cidade
iLnhCidade = iLnhCidade + 1

Wend

'fecha navegador
driver.Quit

'tratamento dos dados

Dim aLnh As Integer
Dim Col As Integer
Dim ValorData
Dim ContData As Integer

ContData = 0

ValorData = Date
ValorData = Format(ValorData, "DD,DDD")

aLnh = 0
Col = 0
 
'TRATAR CABEÇALHO - DIA DA SEMANA COM A HORA
Range("B1").Activate

While ActiveCell.Offset(aLnh + 1, Col).Value <> ""

'ActiveCell.Offset(aLnh + 1, Col).Activate

If ActiveCell.Offset(aLnh + 1, Col) <> 0 Then
    
    ActiveCell.Offset(0, Col) = ValorData

    Else
        ContData = ContData + 1
        ValorData = Date + ContData
        ValorData = Format(ValorData, "DD,DDD")
        ActiveCell.Offset(0, Col) = ValorData
    
End If
Col = Col + 1

Wend
Worksheets("Alerta_Temporal").Range("B1").Activate
End Sub
Segue o arquivo para facilitar o entendimento
download/file.php?mode=view&id=5124

Obrigado a todos!

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Ter Dez 04, 2018 10:59 pm
por webmaster
O que aparece na janela de verificação imediata para a variável da tabela?

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Qua Dez 05, 2018 8:45 pm
por Wagner.cwb
Tomás, estou tentando dessa forma na janela de verificação imediata:

?destino e o resultado é "" - em branco


por curiosidade eu executei o código do seu exemplo - https://www.tomasvasquez.com.br/blog/tag/tabela/

Código: Selecionar todos

Dim driver As WebDriver
 
Sub ExtrairTabelaDaPagina()
    Set driver = New ChromeDriver
    Dim destino As Range
    Set destino = Range("A1")
 
    driver.Get "https://github.com/florentbr/SeleniumBasic"
 
    Dim tabela As WebElement
 
    Set tabela = driver.FindElementByXPath("//div[@id='js-repo-pjax-container']/div[2]/div/div[6]/table")
 
    If tabela Is Nothing Then
        MsgBox "Elemento não encontrado"
    Else
        tabela.AsTable.ToExcel destino
    End If
 
    driver.Quit
End Sub
O resultado da verificação imediata foi

?destino > Type

Eu acredito que o problema é da forma que estou SET o destino... eu preciso que preencha 2 linhas abaixo do último registro.
Eu já tentei de muitas formas, mas mesmo assim não avencei.

Um exemplo que tentei...

Set destino = Worksheets("Alerta_Temporal").Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(0, 0)) - sem cabeçalho

Set destino = Worksheets("Alerta_Temporal").Range(ActiveCell.Offset(2, 0), ActiveCell.Offset(2, 0)) - com cabeçalho

Por favor, pode me ajudar mais nessa rs

abraço!

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Qua Dez 05, 2018 9:24 pm
por Wagner.cwb
Tentei aplicar a solução do Mikel em outro post, mesma coisa... executa normal no debug linha a linha, quando executo via botão... Erro Exceção de HRESULT: 0x800A03EC.

Set destino = ThisWorkbook.Worksheets("Plan2").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)

https://www.tomasvasquez.com.br/forum/v ... php?t=5755
Re: Selenium Basic VBA - Obter dados de uma tabela com varias páginas com XPath e inserir os dados na planilha
Mensagem não lida por Mikel Silveira Fraga » Sáb Dez 02, 2017 11:52 am

Cabelo, boa tarde.

Cara, dei uma olhada no seu código e, mesmo sem conseguir testar, acho que as modificações abaixo podem lhe ajudar.

Faça o seguinte, mude a posição da linha abaixo:
CODE: SELECIONAR TODOS

Set destino = ThisWorkbook.Worksheets("Plan2").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
Para o seguinte local:
CODE: SELECIONAR TODOS

Set destino = ThisWorkbook.Worksheets("Plan2").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
tabela.AsTable.ToExcel destino
Set destino = Nothing 'Adicione essa linha, para limpar a variável da memória.
Acredito que essa alteração deva resolver seu problema.

Teste e nos retorne o resultado.

Abraços e excelente final de semana.

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Qui Dez 06, 2018 5:44 pm
por webmaster
Pedoe, quando disse Janela de Verificação Imediata, quis dizer Janela de Inspeção de Variáveis.

No caso da primeira, às vezes ela só retorna a propriedade padrão. A segunda te dá uma visão melhor do valor da variável.

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Qui Dez 06, 2018 7:29 pm
por Wagner.cwb
Estou há dias pesquisando e não sai do lugar, engraçado que o código avança sem precisar corrigir nada...
sinceramente não sei mais o que pode ser... já testei em outros equipamentos, pois pesquisei na internet e relataram que poderia ser um vírus....
Já mudei a forma de declarar a linha destino... enfim, há alguma chance de você testar no seu equipamento e verificar se passa normal ou se trava no mesmo comando?

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Qui Dez 06, 2018 7:42 pm
por Wagner.cwb
Primeira vez que utilizo esta opção de verificação, desculpe-me, mas segue o print.
Ela me deu uma possível visão do problema... será que estou tendo problemas pq a tabela que estou buscando possui 43 colunas e eu estou definindo no destino somente 1 célula? (Eu estou apenas chutanto por desespero kkkk) Nem mesmo eu acredito, pois no seu exemplo a sua tabela também é maior do que 1...

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Qui Dez 06, 2018 11:34 pm
por webmaster
Foi quase. Ainda gera um erro, mas não é mais do Selenium.

O erro é da própria biblioteca, já que a mensagem gerada vem da própria:

https://stackoverflow.com/questions/127 ... 03ec-error
https://github.com/florentbr/SeleniumBa ... Element.cs

Código: Selecionar todos

Sub extrairTabelasWeb()

    'FALTA TRATAR UNIDADES DE MEDIDAS PARA KM/H

    'https://www.tomasvasquez.com.br/forum/viewtopic.php?t=5755


    Set driver = New ChromeDriver
    'driver.AddArgument ("--headless")
    Dim iLnhCidade As Integer
    Dim URL_Cidade As String
    Dim NomeCidade As String


    iLnhCidade = 2

    While Worksheets("Alerta_Temporal").Range("CM" & iLnhCidade) <> ""

        URL_Cidade = Worksheets("Alerta_Temporal").Range("CQ" & iLnhCidade)
        NomeCidade = Worksheets("Alerta_Temporal").Range("CM" & iLnhCidade)


        Dim Destino As Range

        Worksheets("Alerta_Temporal").Activate
        Worksheets("Alerta_Temporal").Range("B1048576").Activate
        Selection.End(xlUp).Activate

        If ActiveCell.Offset(0, 0).Value <> "" Then
            cabecalho = "nao"

        End If


        'Set Destino = ActiveCell.Offset(0, 0).Range("A1")

        'ActiveCell.Offset(0, 0).Range("A1").Activate
        driver.Timeouts.PageLoad = 5000
        driver.get URL_Cidade, Raise:=False


        Dim tabela As WebElement
        Dim values As Variant

        Set tabela = driver.FindElementById("detail-data-table")

        If tabela Is Nothing Then

            MsgBox "Elemento não encontrado"
        Else
    
            If cabecalho <> "nao" Then
                LnhDest = 1
                'Set Destino = ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "B").End(xlUp).Offset(0, 0)
                Set Destino = Range("B" & LnhDest)
            Else
                'Set Destino = ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "B").End(xlUp).Offset(3, 0)
                LnhDest = 10
                'Set Destino = Range("B" & LnhDest)
                Set Destino = ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "B").End(xlUp).Offset(3, 0)
            End If
            On Error GoTo Trata_Erro
            Dim OutroDestino As Range
            values = tabela.AsTable.Data()
            
            While UBound(values) = 0
                values = tabela.AsTable.Data()
            Wend
            
            Set OutroDestino = Range(Plan1.Cells(Destino.Row, Destino.Column), Plan1.Cells(UBound(values, 2) + Destino.Row, UBound(values, 1) + Destino.Column))
            tabela.AsTable.ToExcel OutroDestino
            Set Destino = Nothing                'Adicione essa linha, para limpar a variável da memória.
    
            If cabecalho = "nao" Then
                Range(ActiveCell.Offset(2, 0), ActiveCell.Offset(5, 43)).Select
                Application.CutCopyMode = False
                Selection.Delete Shift:=xlUp
                ActiveCell.Select
Trata_Erro:
                'tabela.AsTable.ToExcel Destino
                Debug.Print Err.Description
                Debug.Print ErrorCode
                'MsgBox
    
            End If
    
        End If

        If cabecalho = "nao" Then
            ActiveCell.Offset(0, -1) = NomeCidade
            ActiveCell.Offset(1, -1) = "Chuva mm"
            ActiveCell.Offset(2, -1) = "Vento km/h"
            ActiveCell.Offset(3, -1) = "Rajadas km"
            ActiveCell.Offset(4, -1) = "Direcao"

        Else
            ActiveCell.Offset(0, -1) = NomeCidade
        End If



        iLnhCidade = iLnhCidade + 1

    Wend

    driver.Quit
    cabecalho = Nothing
    'tratamento dos dados

    Dim aLnh As Integer
    Dim Col As Integer
    Dim ValorData
    Dim ContData As Integer

    ContData = 0

    ValorData = Date
    ValorData = Format(ValorData, "DD,DDD")

    aLnh = 0
    Col = 0


    'Range("B1") = Date
    '    Range("B1") = Format(Range("B1"), "DD,DDD")
 
    'TRATAR CABEÇALHO - DIA DA SEMANA COM A HORA
    Range("B1").Activate

    While ActiveCell.Offset(aLnh + 1, Col).Value <> ""

        'ActiveCell.Offset(aLnh + 1, Col).Activate

        If ActiveCell.Offset(aLnh + 1, Col) <> 0 Then
    
            ActiveCell.Offset(0, Col) = ValorData

        Else
            ContData = ContData + 1
            ValorData = Date + ContData
            ValorData = Format(ValorData, "DD,DDD")
            ActiveCell.Offset(0, Col) = ValorData
    
        End If
        Col = Col + 1

    Wend

    Worksheets("Alerta_Temporal").Range("B1").Activate
End Sub
Tento postar uma explicação mais detalhada depois.

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Sex Dez 07, 2018 10:02 pm
por Wagner.cwb
Olha, eu sou um cara teimoso kkkk
Eu desconfio também que era um erro fora do selenium, e depois que você pediu para eu investigar a partir da inspeção de variáveis eu fui estudar essa ferramenta e busquei por outra alternativa. Enfim, depois de pesquisar no google encontrei outra maneira de obter as tabelas.
Vou compartilhar aqui, pois pode ajudar outras colegas.
https://github.com/florentbr/SeleniumBasic/issues/63

Eu executei o código do instrutor desse site e percebi que ele obtem a tabela via matriz - values = tbl.AsTable.data() - e a partir daí consegui estabelecer um raciocínio para o meu caso.
Vi, através do inspeção de variáveis, que minha fonte de dados tem uma matriz (8,44) e fiz o seguinte código:

Código: Selecionar todos

'https://github.com/florentbr/SeleniumBasic/issues/63
Sub Verificar_Clima()

Dim iLnhCidade As Integer
Dim URL_Cidade As String
Dim NomeCidade As String
Dim ContCidade As Integer

ContCidade = 0
iLnhCidade = 2

While Worksheets("Alerta_Temporal").Range("CM" & iLnhCidade) <> ""

URL_Cidade = Worksheets("Alerta_Temporal").Range("CQ" & iLnhCidade)
NomeCidade = Worksheets("Alerta_Temporal").Range("CM" & iLnhCidade)
ContCidade = ContCidade + 1

    Dim drv As New ChromeDriver
    drv.Timeouts.PageLoad = 18000 '5000
    drv.get URL_Cidade, Raise:=False

    Dim tbl As WebElement, values()
    Set tbl = drv.FindElementById("detail-data-table", timeout:=19000) '10000
    
    values = tbl.AsTable.data()
    
    Dim IL As Integer 'até 8 linhas
    Dim Col As Integer 'até 44 colunas
    IL = 1
    Col = 1
    Range("a1").Activate
    'leitura da matriz 8x44
    'ler numero de colunas limite - 44
        
        While IL <= UBound(values, 1)
    
        'ir até linha com valor diferente de vazio
        While Col <= UBound(values, 2)
    
            If ContCidade >= 2 Then
    
            Range("A180000").Activate
            Selection.End(xlUp).Activate
            ActiveCell.Offset(3, 0).Range("A1").Activate
    
            ActiveCell.Offset(IL - 1, Col) = values(IL, Col)
    
                Else
                ActiveCell.Offset(IL - 1, Col) = values(IL, Col)
    
    
            End If
    
        Col = Col + 1
        Wend
        IL = IL + 1
    'reinicia coluna depois de encontrar ultimo valor da linha da matriz
        Col = 1
    Wend
    'BUSCA NOVA CIDADE
    iLnhCidade = iLnhCidade + 1
        
    'VERIF SE NECESSITA CABEÇALHO
    If ContCidade >= 2 Then
    
    'ENCONTRAR ULTIMA LINHA
    Range("A180000").Activate
    Selection.End(xlUp).Activate
    ActiveCell.Offset(3, 0).Range("A1").Activate
        
    'APAGAR CABEÇALHO
    Range(ActiveCell.Offset(0, 1), ActiveCell.Offset(2, 44)).Select
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlUp
    ActiveCell.Select
    
    'EDITAR METADOS DADOS SEM CABEÇALHO
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(2, 0) = NomeCidade
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Temperatura"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Chuva mm"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Vento km/h"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Rajadas km"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Direcao"
    
    Else
     
    Dim aLnh As Integer
    Dim ValorData
    Dim ContData As Integer

    'DEFINIR DATA
    ContData = 0

    ValorData = Date
    ValorData = Format(ValorData, "DD,DDD")

    aLnh = 0
    Col = 0
 
'TRATAR CABEÇALHO - DIA DA SEMANA COM A HORA
        Range("B1").Activate

        While ActiveCell.Offset(aLnh + 1, Col).Value <> ""

        If ActiveCell.Offset(aLnh + 1, Col) <> 0 Then
    
        ActiveCell.Offset(0, Col) = ValorData

            Else
            ContData = ContData + 1
            ValorData = Date + ContData
            ValorData = Format(ValorData, "DD,DDD")
            ActiveCell.Offset(0, Col) = ValorData
    
        End If
        Col = Col + 1

        Wend
    'EDITAR METADOS DADOS COM CABEÇALHO
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(0, 0) = "Dia"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Hora"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(2, 0) = NomeCidade
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(0, 0) = "Temperatura"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Chuva mm"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Vento km/h"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Rajadas km"
    ThisWorkbook.Worksheets("Alerta_Temporal").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "Direcao"
    End If
    
Wend

    drv.Quit
    
    'ajustar tamanho das colunas
    ActiveCell.Cells.Select
    ActiveCell.Cells.EntireColumn.AutoFit
    ActiveCell.Select
    'Debug.Assert 0
End Sub
Fiquei animado, mas depois de testar tudo via debug, acreditem... o troço não funcionou :lol: :lol: :lol:
Simplesmente passa batido a captura das tabelas, o script carrega todos os sites, porém muito rápido e não coleta os valores...
Quando faço passo a passo (F8) eu consigo realizar perfeitamente... e fui surpreendido novamente kkkk

Acho que esse é mais fácil para me ajudarem, pois não é um erro, deve ser algum tipo de temporizador que esteja faltando.
Por favor, podem me ajudar mais nessa?

Atualizei o arquivo com o script novo.

Re: AsTable.ToExcel - Erro Exceção de HRESULT: 0x800A03EC

Enviado: Sex Dez 07, 2018 10:48 pm
por Wagner.cwb
Aleluia! Graças a Deus, finalmente kkkkk

Coloquei um - Application.Wait Now + TimeValue("00:00:03") na linha que busca a tabela e os dados carregaram na planilha.

Código: Selecionar todos

Set tbl = drv.FindElementById("detail-data-table", timeout:=10000) '10000
    Application.Wait Now + TimeValue("00:00:03")
Logicamente não irei sossegar até descobrir pq não carrego os dados pelo método "AsTable.ToExcel", mas o projeto poderá avançar.

Agradeço pela a ajuda do Tomás, sempre muito prestativo e espero que este trabalho possa ajudar outras pessoas.

Abraços!