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

Erro de tempo em execução '91' A variavel do objeto ou a variavel do bloco with não foi definida


laertvalois

Pergunta

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.

 

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

 

 

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

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
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...