Notifications
Clear all

Zipar Arquivos / Performance

2 Posts
1 Usuários
0 Reactions
1,260 Visualizações
(@mussato)
Posts: 11
Active Member
Topic starter
 

Bom dia planilheiros,

Tenho uma demanda em que preciso zipar 3 mil arquivos xml. Encontrei um código na internet que resolve meu problema, porém o desempenho é um pouco sofrível, levando quase 1 hora para criar um zip com os 3 mil arquivos xml.

Pelo que entendi do código ele é principalmente prejudicado por ésta linha

Application.Wait (Now + TimeValue("0:00:01"))

Mas nos meus testes, tentar diminuir o tempo de espera resultou em mensagens de erro, esse 1 segundo de espera é provavelmente necessário para manter o arquivo zip aberto.

Se tiverem sugestões, ou exemplos de código que utilizem a solução de zip do windows eu agradeço.

Segue o código abaixo.


Sub Zip_File_Or_Files()
    Dim strDate As String, DefPath As String, sFName As String
    Dim oApp As Object, iCtr As Long, I As Integer
    Dim FName, vArr, FileNameZip
  
    Excel.Application.DisplayAlerts = False
    
    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "" Then
        DefPath = DefPath & ""
    End If

    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"

    'Browse to the file(s), use the Ctrl key to select more files
    FName = Application.GetOpenFilename(filefilter:="Arquivos XML (*.xml*), *.xml*", _ ' trocar para exibir outros tipos de arquivo
                    MultiSelect:=True, Title:="Select the files you want to zip")
    If IsArray(FName) = False Then
        'do nothing
    Else
        'Create empty Zip File
        NewZip (FileNameZip)
        Set oApp = CreateObject("Shell.Application")
        I = 0
        For iCtr = LBound(FName) To UBound(FName)
            vArr = Split97(FName(iCtr), "")
            sFName = vArr(UBound(vArr))
            If bIsBookOpen(sFName) Then
                MsgBox "You can't zip a file that is open!" & vbLf & _
                       "Please close it and try again: " & FName(iCtr)
            Else
                'Copy the file to the compressed folder
                I = I + 1
                oApp.Namespace(FileNameZip).CopyHere FName(iCtr)

                'Keep script waiting until Compressing is done
                On Error Resume Next
                Do Until oApp.Namespace(FileNameZip).items.Count = I
                    Application.Wait (Now + TimeValue("0:00:01"))
                Loop
                On Error GoTo 0
            End If
        Next iCtr
        Excel.Application.DisplayAlerts = True
        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub


Sub NewZip(sPath)
Excel.Application.DisplayAlerts = False
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
    'Excel.Application.DisplayAlerts = True
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
Excel.Application.DisplayAlerts = False
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
    'Excel.Application.DisplayAlerts = True
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
Excel.Application.DisplayAlerts = False
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
    Excel.Application.DisplayAlerts = True
End Function

Encontrei o código aqui

-----
Mussato

V. Mussato
Office Developer
-------------------
Windows 7 64 bits
Office 2013

 
Postado : 28/01/2015 8:37 am
(@mussato)
Posts: 11
Active Member
Topic starter
 
Option Explicit

Sub Zip_File_Or_Files()
    Dim strDate         As String
    Dim DefPath         As String
    Dim sFName          As String
    Dim oApp            As Object
    Dim iCtr            As Long
    Dim I               As Integer
    Dim Fname           As Variant
    Dim vArr            As Variant
    Dim FileNameZip     As Variant
    Dim str             As String
    Dim FSO             As New FileSystemObject
    Dim destino         As String
    Dim cont            As Integer
    Dim pasta           As String
    Dim sub_pasta       As Folder
    Dim FolderName, oFolder
    Dim desktop         As String
    Dim contador        As Integer
    
    Dim fd As Object
    Dim sfd As Object
    
    desktop = CreateObject("WScript.Shell").specialfolders("Desktop")
    
    If Right(desktop, 1) <> "" Then
        desktop = desktop & ""
    End If
    
    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    
    'Define caminho padrão
    FSO.CreateFolder (desktop & "SISCOSERV" & "-" & strDate)
    
    DefPath = desktop & "SISCOSERV" & "-" & strDate
    
    If Right(DefPath, 1) <> "" Then
        DefPath = DefPath & ""
    End If
    
    FileNameZip = DefPath & "SISCOSERV" & "-" & contador & ".zip"
    'Variáveis para nomear pastas

    'Usuário selecionar os arquivos do tipo xml
    Fname = Application.GetOpenFilename(filefilter:="Arquivos XML (*.xml*), *.xml*", _
                    MultiSelect:=True, Title:="Selecione os arquivos XML que você quer zipar")
    
    pasta = "C:UsersViniciusDesktopSISCOCERV_BACKCUPZIP21"
    
    'Cria uma pasta em que os xmls serão copiados
    If FSO.FolderExists(pasta) = False Then
        destino = FSO.CreateFolder(pasta).path
        destino = FSO.CreateFolder(pasta & iCtr).path
    Else
        FSO.DeleteFolder (pasta)
        
        If Right(pasta, 1) <> "" Then
            pasta = pasta & ""
        Else
            Exit Sub
        End If
        
        destino = FSO.CreateFolder(pasta).path
        destino = FSO.CreateFolder(pasta & iCtr).path
    End If
        
    'executa looping em todos os arquivos selecionados, copiando-os em pastas em grupos de 200
    For iCtr = LBound(Fname) To UBound(Fname)
         
          If cont = 200 Then
             'renomeia a pasta
             destino = FSO.CreateFolder(pasta & iCtr).path
             cont = 0
          End If
         
         'copia arquivo na pasta
         Call FSO.CopyFile(Fname(iCtr), destino & "_" & Dir(Fname(iCtr)), True)
         
         'incrementa contador
         cont = cont + 1
              
    Next iCtr
    
    Set fd = FSO.GetFolder(pasta)
    
    For Each sfd In fd.SubFolders
     
    Set oApp = CreateObject("Shell.Application")

    'Browse to the folder
    Set oFolder = sfd
    If Not oFolder Is Nothing Then
        'Create empty Zip File
        NewZip (FileNameZip)
        
        FolderName = oFolder
        If Right(FolderName, 1) <> "" Then
            FolderName = FolderName & ""
        End If

        'Copy the files to the compressed folder
        oApp.Namespace(FileNameZip).CopyHere oApp.Namespace(FolderName).items

        'Keep script waiting until Compressing is done
        On Error Resume Next
        Do Until oApp.Namespace(FileNameZip).items.count = _
        oApp.Namespace(FolderName).items.count
            Application.Wait (Now + TimeValue("0:00:01"))
        Loop
        On Error GoTo 0
        contador = contador + 1
        FileNameZip = DefPath & "SISCOSERV" & "-" & contador & ".zip"
    
    End If
    
    Next
    
End Sub



Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
    'Excel.Application.DisplayAlerts = True
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
Excel.Application.DisplayAlerts = False
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
    'Excel.Application.DisplayAlerts = True
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
Excel.Application.DisplayAlerts = False
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
    Excel.Application.DisplayAlerts = True
End Function

V. Mussato
Office Developer
-------------------
Windows 7 64 bits
Office 2013

 
Postado : 05/02/2015 11:47 am