Inquiridor
Erro em tempo de execução '91'

Discussão Geral
-
Olá amigos, sábios, jedis, magos e mestres do VBA e outros colaboradores.
Criei uma macro que, através de uma variável, realiza uma importação dos dados de uma página web da intranet do meu trabalho. Tudo funciona bem, mas somente após eu fazer uma acesso à página pelo próprio Excel.
Nesta pasta tenho duas planilhas: a "DadosImportados" que é uma planilha vazia, para importação dos dados; e a planilha "ROTEIRO" que é preenchida com os dados importados.
Quando eu abro a planilha, se eu clicar imediatamente no botão de importação, me ocorre o "Erro de tempo em execução '91' A variavel do objeto ou a variavel do bloco with não foi definida". Fazendo o debug passo-a-passo com F8 percebi que os dados não estão sendo importados.
Depois de alguns testes descobri que a macro só funciona corretamente após ir na planilha "DadosImportados" e clicar com o direito do mouse, escolher a opção "Editar consulta". Feito isso abre o navegador do excel e não preciso esperar a página carregar, apenas clico no botão "Cancelar". Após fazer isso a macro funciona corretamente.
Gostaria de utilizar a pasta sem precisar ter que ir em "Editar Consulta". É como se fizesse necessário acessar a página antes para a consulta funcionar.*NOTA = Código funciona corretamente no EXCEL 2007, o erro só é apresentado no 2013.
Sub ImportaDadosS400() ' ' Macro para importação de dados do S400 ' 'Declaração das variáveis Dim sicad As String Dim nome As String Dim cpf As String Dim agencia As String Dim status As String Dim val_cad As String Dim val_cad_date As Date Dim porte As String Dim segmento As String Dim atividade As String Dim renda As String Dim renda_num As Currency Dim logradouro As String Dim bairro As String Dim cidade As String Dim cep As String Dim endereco As String Dim filiacao As String Dim naturalidade As String Dim dt_nascimento As String Dim identidade As String Dim org_expedidor As String Dim dt_emissao As String Dim estado_civil As String Dim p As LongPtr Dim i As LongPtr Application.ScreenUpdating = False sicad = Sheets("ROTEIRO").Range("SICAD1").Value Sheets("DadosImportados").Select If sicad = "" Then MsgBox "Favor preencher o sicad apenas com números." & Chr(10) & "" & Chr(10) & " Clique em OK", vbOKOnly, "SICAD NÃO PREENCHIDO" Sheets("ROTEIRO").Select Range("SICAD1").Select Exit Sub Else MsgBox "O processo de busca dura entre 10 e 40 segundos." & Chr(10) & "" & Chr(10) & " Clique em OK", vbOKCancel, "FIQUE TRANQUILO" With ActiveSheet.QueryTables.Add(Connection:= _ "URL;http://d001mfp1/S400-CCClientes/faces/_rlvid.jsp?_rap=pc_ConsultarCadastrosLista.doRowAction1Action&_rvip=/consultarCadastros.jsp&codigoClienteParam=" & sicad _ , Destination:=Range("$A$1")) .Name = "cadastro" & sicad .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = False .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .WebSelectionType = xlSpecifiedTables .WebFormatting = xlWebFormattingNone .WebTables = """tabelaFiltroSecao""" .WebPreFormattedTextToColumns = True .WebConsecutiveDelimitersAsOne = True .WebSingleBlockTextImport = False .WebDisableDateRecognition = False .WebDisableRedirections = False .Refresh BackgroundQuery:=False End With Sheets("DadosImportados").Select Cells.Find(What:="Nome", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate nome = ActiveCell.Value Cells.Find(What:="CPF", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate cpf = ActiveCell.Value Cells.Find(What:="Agência Responsável", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate agencia = ActiveCell.Value Cells.Find(What:="Situação de Cadastro", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate status = ActiveCell.Value Cells.Find(What:="Próxima Renovação", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate val_cad = ActiveCell.Value Cells.Find(What:="Porte", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate porte = ActiveCell.Value Cells.Find(What:="Segmento", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate segmento = ActiveCell.Value Cells.Find(What:="Atividade Principal", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate atividade = ActiveCell.Value Cells.Find(What:="Renda Bruta Mensal", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate renda = ActiveCell.Value Cells.Find(What:="ENDEREÇO RESIDENCIAL", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate ActiveCell.Offset(1, 0).Select logradouro = ActiveCell.Value ActiveCell.Offset(1, 0).Select bairro = ActiveCell.Value Cells.Find(What:="cidade", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate cidade = ActiveCell.Value Cells.Find(What:="CEP", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate cep = ActiveCell.Value Cells.Find(What:="Filiação", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate filiacao = ActiveCell.Value Cells.Find(What:="Natural de", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate naturalidade = ActiveCell.Value Cells.Find(What:="Data de Nascimento", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate dt_nascimento = ActiveCell.Value Cells.Find(What:="Identidade", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate identidade = ActiveCell.Value Cells.Find(What:="Órgão Emissor", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate org_expedidor = ActiveCell.Value Cells.Find(What:="Data de Emissão", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate dt_emissao = ActiveCell.Value Cells.Find(What:="Estado Civil", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate estado_civil = ActiveCell.Value nome = Replace(nome, "Nome: ", "") cpf = Replace(cpf, "CPF: ", "") agencia = Replace(agencia, "Agência Responsável: ", "") agencia = Left(agencia, 3) status = Replace(status, "Situação de Cadastro: ", "") val_cad = Replace(val_cad, "Próxima Renovação: ", "") val_cad_date = val_cad porte = Replace(porte, "Porte: ", "") segmento = Replace(segmento, "Segmento: ", "") atividade = Replace(atividade, "Atividade Principal: ", "") renda = Replace(renda, "Renda Bruta Mensal: R$ ", "") renda_num = renda logradouro = Replace(logradouro, "Logradouro: ", "") bairro = Replace(bairro, "Bairro: ", "") cidade = Replace(cidade, "Cidade: ", "") endereco = logradouro & ", " & bairro & ", " & cidade & ", " & cep filiacao = Replace(filiacao, "Filiação: ", "") naturalidade = Replace(naturalidade, "Natural de: ", "") dt_nascimento = Replace(dt_nascimento, "Data de Nascimento: ", "") identidade = Replace(identidade, "Identidade: ", "") org_expedidor = Replace(org_expedidor, "Órgão Emissor: ", "") dt_emissao = Replace(dt_emissao, "Data de Emissão: ", "") estado_civil = Replace(estado_civil, "Estado Civil: ", "") Sheets("ROTEIRO").Select Sheets("ROTEIRO").Range("NOME").Value = nome Sheets("ROTEIRO").Range("CPFNOME").Value = cpf Sheets("ROTEIRO").Range("AGENCIA1").Value = agencia Sheets("ROTEIRO").Range("STATUS_CADASTRO1").Value = status Sheets("ROTEIRO").Range("VALIDADE_CADASTRO1").Value = val_cad_date Sheets("ROTEIRO").Range("PORTE1").Value = porte Sheets("ROTEIRO").Range("SEGMENTO1").Value = segmento Sheets("ROTEIRO").Range("ATIVIDADE1").Value = atividade Sheets("ROTEIRO").Range("RENDA1").Value = renda_num Sheets("ROTEIRO").Range("ENDERECO1").Value = endereco Sheets("ROTEIRO").Range("FILIACAO1").Value = filiacao Sheets("ROTEIRO").Range("NATURALIDADE1").Value = naturalidade Sheets("ROTEIRO").Range("DT_NASCIMENTO1").Value = dt_nascimento Sheets("ROTEIRO").Range("IDENTIDADE1").Value = identidade Sheets("ROTEIRO").Range("ORG_EMISSOR1").Value = org_expedidor Sheets("ROTEIRO").Range("DT_EMISSAO1").Value = dt_emissao Sheets("ROTEIRO").Range("EST_CIVIL1").Value = estado_civil 'Sheets("DadosImportados").Range("b26").Value = DateValue(data) Sheets("DadosImportados").Select Cells.Select Selection.ClearContents 'Call Excluiplanilha End If MsgBox "Dados importados com sucesso!" & Chr(10) & "" & Chr(10) & " Clique em OK e verifique os dados.", vbOKOnly, "Importação concluída" Application.ScreenUpdating = True Sheets("ROTEIRO").Select Range("STATUS_CADASTRO").Select End Sub
Todas as Respostas
-
Olá, Laert,
boa tarde.
Experimente (se é que você já não tentou isto) fazer o seguinte:
- Habilite todas as Macros no 2013 em : Arquivo > Opções > Central de Confiabilidade > Configurações da Central de Confiabilidade... > Configurações de Macro > Habilitar todas as macros
- Altere a extensão do arquivo para xltm, desta forma: Arquivo > Salvar como... e altere o Tipo para Modelo Habilitado para Macro do Excel
O idioma do Excel da versão 2007 era o mesmo da versão 2013?
Aguardo
Abs.
-
Olá Herbert,
Obrigado pelo retorno.
As macros já estavam habilitadas, mas não havia salvo ainda como xltm. Salvei com essa extensão mas o erro persiste.
Em alguns testes o ele indica que a consulta à web não retornou resultados.
Sobre o idioma você quer dizer português?
Eu fiz essa macro direto no Excel 2013, inicialmente através do Gravar Macro (pelo menos a parte de importar dados da Web). O engraçado é que sempre que eu fecho o arquivo ele deixa de funcionar, mas se eu abro no Excel 2007 ele não dá erro algum.
No 2013 quando eu clico no botão para rodar a macro ele apresenta o erro '91'. Então vou até a planilha que que os dados serão importados, clico na célula A1 (mas pode ser outras) com o botão direito e depois em "Editar consulta", o browser do Excel abre e, nem precisa carregar a página, aperto em cancelar.
Depois que faço isso, a macro roda redondinha. Já percebi isso em outro arquivo também. -
-
Oi Herbert,
Salvei como modelo e está funcionando. Apresenta um erro, bem verdade, mas é só dar um OK e depois a a macro roda.
O erro é esse:
Esta consulta à Web não retornou dados. Para alterar a consulta, clique em OK, clique na seta na caixa de nome na barra de fórmulas, clique no nome do intervalo de dados externo da consulta à Web, clique com o botão direito do mouse na seleção e cliquem em Editar Consulta.
Não coloquei o print pois o forum está pedindo para eu confirmar minha conta. Mas não encontrei essa opção.
-