Notifications
Clear all

Erro: "Application-defined or object-defined error"

10 Posts
2 Usuários
0 Reactions
1,608 Visualizações
(@outofmemry)
Posts: 0
New Member
Topic starter
 

Preciso de ajuda para resolver este problema pois sou iniciante em vba para excel e não percebo muito disto.
O erro é este: "Run-time error 1004 " "Application-defined or object-defined error"

Ocorre no fim do meu codigo quando esta a fazer o Delete. Aqui esta o código:

   Function Copy()

    Dim shtSrc As Worksheet, shtDest As Worksheet
    Dim lRow As Long, Row As Long, viewmode
    Dim countA As Long, countB As Long
    Dim t As Double, rw As Range, rngDel As Range

    lRow = 5000
    Row = 2
    countA = 0
    countB = 0

    Set shtSrc = Worksheets("Sheet1")
    Set shtDest = Worksheets("Sheet2")

    shtSrc.Range("A1:AQ1").Copy Destination:=shtDest.Range("A1")

    Application.ScreenUpdating = False
    viewmode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    Application.EnableEvents = False
    Application.DisplayStatusBar = False

    ActiveSheet.DisplayPageBreaks = False

    t = Timer

     Do While lRow > 2

            Set rw = shtSrc.Rows(lRow)

            If (rw.Cells(2) = rw.Cells(2).Offset(-1, 0)) Then

                If (rw.Cells(3) > rw.Cells(3).Offset(-1, 0)) Then
                    rw.Offset(-1, 0).Copy shtDest.Rows(Row)
                    AddToRange rngDel, rw.Offset(-1, 0)
                    countA = countA + 1
                Else
                    rw.Copy shtDest.Rows(Row)
                    AddToRange rngDel, rw
                    countB = countB + 1
                End If

                Row = Row + 1

           End If

           lRow = lRow - 1

    Loop

    'anything to delete?
    If Not rngDel Is Nothing Then
        rngDel.Delete                                    ' O ERRO ocorre quando aqui chega
    End If

    Application.DisplayStatusBar = True
    ActiveWindow.View = viewmode
    Application.ScreenUpdating = False
    MsgBox "A = " & countA & " B = " & countB & "Time (minutes): " & (Timer - t) / 60

End Function

'utility sub for building up a range
Sub AddToRange(rngTot, rng)
    If rngTot Is Nothing Then
        Set rngTot = rng
    Else
        Set rngTot = Application.Union(rng, rngTot)
    End If
End Sub
 
Postado : 29/10/2015 7:32 am
(@fernandofernandes)
Posts: 43750
Illustrious Member
 

Bom dia!!

Você tem código em sua postagem, o primeiro

 Function Copy()

Apenas apareceu uma Caixa de mensagem após a execução (eu não tive o erro), o segundo não foi testado!

Att

 
Postado : 29/10/2015 7:42 am
(@outofmemry)
Posts: 0
New Member
Topic starter
 

Já percebi porque de estar a dar erro. Eu estou a testar em tabelas de 5k linhas, para poder usar em tabelas de 65k linhas, mas mesmo nas tabelas de 5k linhas da o erro.
Caso use em tabelas pequenas não ocorre erro nenhum.

 
Postado : 29/10/2015 7:57 am
(@fernandofernandes)
Posts: 43750
Illustrious Member
 

Boa tarde!!

Para um melhor e mais eficiente retorno, poste uma arquivo modelo compactado, nele explicite e exemplifique seu resultado pretendido!!!

Att

 
Postado : 29/10/2015 9:53 am
(@outofmemry)
Posts: 0
New Member
Topic starter
 

Isto é uma tabela exmplo:
A | B | C
243|02-10-2015 12:15:30 | 05-10-2015 22:50:00
243|10-08-2015 15:12:05 | 17-08-2015 11:33:22
167|14-04-2015 11:07:45 | 14-04-2015 11:46:30

Tabela1 exemplo pretendida:

A | B | C
243|02-10-2015 12:15:30 | 05-10-2015 22:50:00
167|14-04-2015 11:07:45 | 14-04-2015 11:46:30

Tabela2 exemplo pretendida:
A | B | C
243|10-08-2015 15:12:05 | 17-08-2015 11:33:22

Ou seja quero que o código verifique em uma coluna se tem valores repetidos, caso sim vai ver qual tem o maior valor em B, copiando a linha de menor valor para uma tabela2 e apagando-a da tabela1.
Isto tudo tem de ser feito em tabelas de cerca 65,000 linhas e este código só está a funcionar até tabelas de 1.000 linhas.

PS: Possuo outro codigo que faz tudo direito e rápido em tabelas de 65k linhas, no entanto é um código confuso e que me desformata as colunas das datas, fazendo com que as perca.

 
Postado : 29/10/2015 10:51 am
(@fernandofernandes)
Posts: 43750
Illustrious Member
 

Talvez a montagem da range rngTot esteja sendo gerada com erro, ou muito grande para capacidade de memoria disonivel.
De uma lida em http://www.cpearson.com/excel/BetterUnion.aspx talvez auxilie

 
Postado : 29/10/2015 10:56 am
(@outofmemry)
Posts: 0
New Member
Topic starter
 

Bem eu não sei o que se passou, pois testei o código durante cerca de uma semana e nunca funcionou. Agora voltei a testar sem querer e funcionou. Peço desculpa pelo tempo perdido e obrigado por tentar ajudar.

PS: Apesar de funcionar este código leva imenso tempo a fazer o pretendido, para terem um ideia nas tabelas de 5k linhas demorou +/- 1:50 min. O outro código que tenho faz o mesmo em poucos segundos, para tabelas de 65k linhas demora 12s, no entanto desformata as duas colunas de datas ficando sem elas. (exemplo: inicialmente a data e assim 29-09-2015 13:04:34, ficando depois na tabela ############ e na barra de formulas 42276544837963). Será que seria possível colocar aqui esse código para me tentarem ajudar a corrigir isto? (PS2: Eu não sei explicar o código, pois foi retirado de outro forum onde coloquei a duvida e o autor dele também ainda não conseguiu descobrir o problema).

 
Postado : 29/10/2015 11:29 am
(@fernandofernandes)
Posts: 43750
Illustrious Member
 

As "hash tag's" são exibidas quando o valor para data/hora são negativos e/ou muito grandes para exibir na celula.
Pelo que descreve é um valor muito grande.
Disponibilize o codigo, ou o link onde está, que podemos tentar ajudar, sem compromisso

 
Postado : 30/10/2015 8:41 am
(@outofmemry)
Posts: 0
New Member
Topic starter
 

Sim o numero é grande, mas eu já alarguei a célula e fica sempre assim, no entanto não era suposto lá estar aquele numero mas sim datas.
O código é o seguinte:

Sub Keep_Highest_BC()
    Dim d As Long, dHIGHs As Object, dDUPEs As Object
    Dim v As Long, vTMPs() As Variant, iCOLs As Long

    Debug.Print Timer
    'On Error GoTo bm_Safe_Exit
    Set dHIGHs = CreateObject("Scripting.Dictionary")
    Set dDUPEs = CreateObject("Scripting.Dictionary")

    With Worksheets("Sheet1")
        iCOLs = .Columns("AQ").Column
        .Cells(1, 1).Resize(2, iCOLs).Copy _
          Destination:=Worksheets("Sheet2").Cells(1, 1)
        With .Cells(2, 1).Resize(.Cells(Rows.Count, 2).End(xlUp).Row - 1, iCOLs)
            vTMPs = .Value2
        End With
    End With

    For v = LBound(vTMPs, 1) To UBound(vTMPs, 1)
        If dHIGHs.exists(vTMPs(v, 2)) Then
            If CDbl(Split(dHIGHs.Item(vTMPs(v, 2)), ChrW(8203))(2)) < vTMPs(v, 3) Then
                dDUPEs.Add Key:=vTMPs(v, 2) & v, Item:=dHIGHs.Item(vTMPs(v, 2))
                dHIGHs.Item(vTMPs(v, 2)) = joinAtoAQ(vTMPs, v)
            Else
                dDUPEs.Add Key:=vTMPs(v, 2) & v, Item:=joinAtoAQ(vTMPs, v)
            End If
        Else
            dHIGHs.Add Key:=vTMPs(v, 2), Item:=joinAtoAQ(vTMPs, v)
        End If
    Next v

    With Worksheets("Sheet1")
        With .Cells(2, 1).Resize(.Cells(Rows.Count, 2).End(xlUp).Row - 1, iCOLs)
            .ClearContents
            With .Resize(dHIGHs.Count, iCOLs)
                .Value = transposeSplitLargeItemArray(dHIGHs.items)
            End With
        End With
    End With

    With Worksheets("Sheet2")
        With .Cells(1, 1).CurrentRegion.Offset(1, 0)
            .ClearContents
            With .Resize(dDUPEs.Count, iCOLs)
                .Value = transposeSplitLargeItemArray(dDUPEs.items)
                .Rows(1).Copy
                .PasteSpecial Paste:=xlPasteFormats
                Application.CutCopyMode = False
            End With
        End With
    End With

bm_Safe_Exit:
    dHIGHs.RemoveAll: Set dHIGHs = Nothing
    dDUPEs.RemoveAll: Set dDUPEs = Nothing

    Debug.Print Timer
End Sub

Function joinAtoAQ(vTMP As Variant, ndx As Long)
    Dim sTMP As String, v As Long

    For v = LBound(vTMP, 2) To UBound(vTMP, 2)
        sTMP = sTMP & vTMP(ndx, v) & ChrW(8203)
    Next v
    joinAtoAQ = Left$(sTMP, Len(sTMP) - 1)
End Function

Function transposeSplitLargeItemArray(vITMs As Variant)
    Dim v As Long, w As Long, vTMPs As Variant, vITM As Variant

    ReDim vTMPs(LBound(vITMs) To UBound(vITMs), LBound(vITMs) To UBound(Split(vITMs(LBound(vITMs)), ChrW(8203))))
    For v = LBound(vITMs) To UBound(vITMs)
        vITM = Split(vITMs(v), ChrW(8203))
        For w = LBound(vITM) To UBound(vITM)
            vTMPs(v, w) = vITM(w)
        Next w
    Next v

    transposeSplitLargeItemArray = vTMPs
End Function
 
Postado : 30/10/2015 10:51 am
(@fernandofernandes)
Posts: 43750
Illustrious Member
 

Na realidade são varias rotinas que executam uma atividade, assim da minha parte somente "acompanhando" a execução da mesma para tentar descobrir onde a "transformação" acontece. se pude dispor de um modelo?

 
Postado : 30/10/2015 2:39 pm