Propósito

✔ Programação GLOBAL® - Quaisquer soluções e/ou desenvolvimento de aplicações pessoais, ou da empresa, que não constem neste Blog devem ser tratados como consultoria freelance. Queiram contatar-nos: brazilsalesforceeffectiveness@gmail.com | ESTE BLOG NÃO SE RESPONSABILIZA POR QUAISQUER DANOS PROVENIENTES DO USO DOS CÓDIGOS AQUI POSTADOS EM APLICAÇÕES PESSOAIS OU DE TERCEIROS.

Mostrando postagens com marcador Ron de Bruin. Mostrar todas as postagens
Mostrando postagens com marcador Ron de Bruin. Mostrar todas as postagens

PIECE OF CAKE - MS Excel - Zipando - Compacte no formato Zip usando o programa padrão do Windows - Zip file(s) with the default Windows zip program (VBA)



Copie o código abaixo num módulo padrão de sua planilha.

O código abaixo não é suportado pela Microsoft.
Não é possível ocultar a caixa de diálogo de cópia quando copia para uma pasta zip (isso só funciona com pastas normais, até onde eu sei). Também não há possibilidade de evitar que alguém possa cancelar a operação ou que seu código VBA notifique algo caso a operação seja cancelada.

Não redimensione, por exemplo, FileNameZip como String nos exemplos de código. Essa deve ser Variant, caso contrário, o código não funcionará.

Sub NewZip (sPath)
    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
End Sub


Function bIsBookOpen (ByRef szBookName As String) As Boolean

    On Error Resume Next

    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function

Function Split97 (sStr As Variant, sdelim As String) As Variant
    Let Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
End Function


Veja também:



#A&A #PIECEOFCAKE #POC #VBA #RondeBruin #MS #Excel



Consulte-nos

⬛◼◾▪ Social Media ▪◾◼⬛
• FACEBOOK • TWITTER • INSTAGRAM • TUMBLR • GOOGLE+ • LINKEDIN • PINTEREST

⬛◼◾▪ Blogs ▪◾◼⬛ 


⬛◼◾▪ CONTATO ▪

PIECE OF CAKE - MS Excel - Zipando - Abra uma Janela e Escolha os Arquivos que deseja Compacatar - Browse to the folder you want and select the file or files

Título auto-explicativo.


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

    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:="Excel Files (*.xl*), *.xl*", _
                    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

        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub



#A&A #PIECEOFCAKE #POC #VBA #RondeBruin #MS #Excel

Veja também:



Consulte-nos

⬛◼◾▪ Social Media ▪◾◼⬛
• FACEBOOK • TWITTER • INSTAGRAM • TUMBLR • GOOGLE+ • LINKEDIN • PINTEREST

⬛◼◾▪ Blogs ▪◾◼⬛ 


⬛◼◾▪ CONTATO ▪

PIECE OF CAKE - MS Excel - Zipando - Escolha uma Pasta e Compacte Tudo Nela - Browse to a folder and zip all files in it


Bem, o título já descreve bem a ação deste código.

Sub Zip_All_Files_in_Folder_Browse()
    Dim FileNameZip, FolderName, oFolder
    Dim strDate As String, DefPath As String
    Dim oApp As Object

    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"

    Set oApp = CreateObject("Shell.Application")

    'Browse to the folder
    Set oFolder = oApp.BrowseForFolder(0, "Select folder to Zip", 512)
    If Not oFolder Is Nothing Then
        'Create empty Zip File
        NewZip (FileNameZip)

        FolderName = oFolder.Self.Path
        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

        MsgBox "You find the zipfile here: " & FileNameZip

    End If
End Sub


#A&A #PIECEOFCAKE #POC #VBA #RondeBruin #MS #Excel

Veja também:


Consulte-nos

⬛◼◾▪ Social Media ▪◾◼⬛
• FACEBOOK • TWITTER • INSTAGRAM • TUMBLR • GOOGLE+ • LINKEDIN • PINTEREST

⬛◼◾▪ Blogs ▪◾◼⬛ 


⬛◼◾▪ CONTATO ▪

PIECE OF CAKE - MS Excel - Zipando - Compacte Todos os Arquivos Contidos na Pasta Informada no Código - Zip all files in the folder that you enter in the code


Antes de executar este código, altere a pasta na linha 
FolderName = "C: \ Bernardes \"



Sub Zip_All_Files_in_Folder()
    Dim FileNameZip, FolderName
    Dim strDate As String, DefPath As String
    Dim oApp As Object

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    FolderName = "C:\Bernardes\"    '<< Change

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

    'Create empty Zip File
    NewZip (FileNameZip)

    Set oApp = CreateObject("Shell.Application")

    '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

    MsgBox "You find the zipfile here: " & FileNameZip
End Sub



#A&A #PIECEOFCAKE #POC #VBA #RondeBruin #MS #Excel
Consulte-nos

⬛◼◾▪ Social Media ▪◾◼⬛
• FACEBOOK • TWITTER • INSTAGRAM • TUMBLR • GOOGLE+ • LINKEDIN • PINTEREST

⬛◼◾▪ Blogs ▪◾◼⬛ 


⬛◼◾▪ CONTATO ▪

PIECE OF CAKE - MS Excel - Zipando - Compactando a Planilha Atual - Zip the ActiveWorkbook


Este script faz uma cópia do Activeworkbook e o compacta em "C: \ Bernardes \" com um carimbo de data e hora. Altere esta pasta ou use seu caminho padrão Application.DefaultFilePath


Sub Zip_ActiveWorkbook()
    Dim strDate As String, DefPath As String
    Dim FileNameZip, FileNameXls
    Dim oApp As Object
    Dim FileExtStr As String

    DefPath = "C:\Bernardes\"    '<< Change
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    'Create date/time string and the temporary xl* and Zip file name
    If Val(Application.Version) < 12 Then
        FileExtStr = ".xls"
    Else
        Select Case ActiveWorkbook.FileFormat
        Case 51: FileExtStr = ".xlsx"
        Case 52: FileExtStr = ".xlsm"
        Case 56: FileExtStr = ".xls"
        Case 50: FileExtStr = ".xlsb"
        Case Else: FileExtStr = "notknown"
        End Select
        If FileExtStr = "notknown" Then
            MsgBox "Sorry unknown file format"
            Exit Sub
        End If
    End If

    strDate = Format(Now, " yyyy-mm-dd h-mm-ss")
    
    FileNameZip = DefPath & Left(ActiveWorkbook.Name, _
    Len(ActiveWorkbook.Name) - Len(FileExtStr)) & strDate & ".zip"
    
    FileNameXls = DefPath & Left(ActiveWorkbook.Name, _
    Len(ActiveWorkbook.Name) - Len(FileExtStr)) & strDate & FileExtStr

    If Dir(FileNameZip) = "" And Dir(FileNameXls) = "" Then

        'Make copy of the activeworkbook
        ActiveWorkbook.SaveCopyAs FileNameXls

        'Create empty Zip File
        NewZip (FileNameZip)

        'Copy the file in the compressed folder
        Set oApp = CreateObject("Shell.Application")
        oApp.Namespace(FileNameZip).CopyHere FileNameXls

        'Keep script waiting until Compressing is done
        On Error Resume Next
        Do Until oApp.Namespace(FileNameZip).items.Count = 1
            Application.Wait (Now + TimeValue("0:00:03"))
        Loop
        On Error GoTo 0
        'Delete the temporary xls file
        Kill FileNameXls

        MsgBox "Your Backup is saved here: " & FileNameZip

    Else
        MsgBox "FileNameZip or/and FileNameXls exist"

    End If
End Sub


#A&A #PIECEOFCAKE #POC #VBA #RondeBruin #MS #Excel
Consulte-nos

⬛◼◾▪ Social Media ▪◾◼⬛
• FACEBOOK • TWITTER • INSTAGRAM • TUMBLR • GOOGLE+ • LINKEDIN • PINTEREST

⬛◼◾▪ Blogs ▪◾◼⬛ 


⬛◼◾▪ CONTATO ▪

PIECE OF CAKE - MS Excel - Zipando - Compactando e Enviando por e-Mail - Zip and mail the ActiveWorkbook


Este código foi escrito para que estiver usando o Outlook como seu programa de e-mail.

Este código enviará a planilha recém-criada (cópia do seu Activeworkbook). Guardará o zip na pasta de trabalho antes de enviá-lo com um carimbo de data | hora. Depois que o arquivo zip for enviado, o arquivo zip e a pasta de trabalho serão excluídos.


Sub Zip_Mail_ActiveWorkbook()
    Dim strDate As String, DefPath As String, strbody As String
    Dim oApp As Object, OutApp As Object, OutMail As Object
    Dim FileNameZip, FileNameXls
    Dim FileExtStr As String

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    'Create date/time string and the temporary xl* and zip file name
    If Val(Application.Version) < 12 Then
        FileExtStr = ".xls"
    Else
        Select Case ActiveWorkbook.FileFormat
        Case 51: FileExtStr = ".xlsx"
        Case 52: FileExtStr = ".xlsm"
        Case 56: FileExtStr = ".xls"
        Case 50: FileExtStr = ".xlsb"
        Case Else: FileExtStr = "notknown"
        End Select
        If FileExtStr = "notknown" Then
            MsgBox "Sorry unknown file format"
            Exit Sub
        End If
    End If

    strDate = Format(Now, " yyyy-mm-dd h-mm-ss")

    FileNameZip = DefPath & Left(ActiveWorkbook.Name, _
    Len(ActiveWorkbook.Name) - Len(FileExtStr)) & strDate & ".zip"

    FileNameXls = DefPath & Left(ActiveWorkbook.Name, _
    Len(ActiveWorkbook.Name) - Len(FileExtStr)) & strDate & FileExtStr


    If Dir(FileNameZip) = "" And Dir(FileNameXls) = "" Then

        'Make copy of the activeworkbook
        ActiveWorkbook.SaveCopyAs FileNameXls

        'Create empty Zip File
        NewZip (FileNameZip)

        'Copy the file in the compressed folder
        Set oApp = CreateObject("Shell.Application")
        oApp.Namespace(FileNameZip).CopyHere FileNameXls

        'Keep script waiting until Compressing is done
        On Error Resume Next
        Do Until oApp.Namespace(FileNameZip).items.Count = 1
            Application.Wait (Now + TimeValue("0:00:01"))
        Loop
        On Error GoTo 0

        'Create the mail
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)
        strbody = "Hi there" & vbNewLine & vbNewLine & _
                  "This is line 1" & vbNewLine & _
                  "This is line 2" & vbNewLine & _
                  "This is line 3" & vbNewLine & _
                  "This is line 4"

        On Error Resume Next
        With OutMail
            .To = "ron@debruin.nl"
            .CC = ""
            .BCC = ""
            .Subject = "This is the Subject line"
            .Body = strbody
            .Attachments.Add FileNameZip
            .Send   'or use .Display
        End With
        On Error GoTo 0

        'Delete the temporary Excel file and Zip file you send
        Kill FileNameZip
        Kill FileNameXls
    Else
        MsgBox "FileNameZip or/and FileNameXls exist"
    End If
End Sub


#A&A #PIECEOFCAKE #POC #VBA #RondeBruin #MS #Excel

Veja também:



Consulte-nos

⬛◼◾▪ Social Media ▪◾◼⬛
• FACEBOOK • TWITTER • INSTAGRAM • TUMBLR • GOOGLE+ • LINKEDIN • PINTEREST

⬛◼◾▪ Blogs ▪◾◼⬛ 


⬛◼◾▪ CONTATO ▪

VBA Tips - Apagando Arquivos - Delete Files and Folders


Veja também:

MS Excel – Diversas Funções Úteis

É bem provável que já tenha precisado de algo similar no MS Excel, mas não teve a oportunidade de encontrar essa informação de modo organizado, como estou propondo colocar abaixo.

Ao gerarmos os nossos diversos Relatórios, inclusive Dashboards, invariavelmente precisaremos gravar as versões em pastas.

Digamos que deseje gravar as informações geradas nas pastas customizadas, talvez com a data do momento da geração. Precisaríamos criar uma pasta para a transferência dos mesmos.

É importante frisar que não há como recuperar o arquivo excluído uma vez que o tenhamos deletado. O arquivo não é enviado para a lixeira do Windows.

Em qualquer um dos códigos listados neste artigo, ao executar um código VBA que inclua a instrução Kill, o código poderá excluir todos os arquivos armazenados em uma pasta ou em um servidor de rede.

Sub DelSample001()
 ' Você pode usar este código para apagar todos os arquivos na pasta de teste.
    On Error Resume Next

    Kill "E:\Bernardes\Dashboards\*.*"

    On Error GoTo 0
End Sub

Sub DelSample002()
 ' Você pode usar este código para apagar todos os arquivos xl? na pasta de teste.
    On Error Resume Next
    Kill "E:\Bernardes\Dashboards\*.xl*"
    On Error GoTo 0
End Sub

Sub DelSample003()
 ' Você pode usar este código para apagar um arquivo xls na pasta de teste.
    On Error Resume Next

    Kill "E:\Bernardes\Dashboards\ron.xls"
    On Error GoTo 0
End Sub

Sub DelSample004()
 ' Você pode usar este código para apagar a pasta inteira.
 ' Note: RmDir delete only a empty folder
    On Error Resume Next

    Kill "E:\Bernardes\Dashboards\*.*"    ' delete all files in the folder

    RmDir "E:\Bernardes\Dashboards\"  ' delete folder

    On Error GoTo 0
End Sub

Sub Delete_Whole_Folder()
' Você pode usar este código para apagar a pasta inteira sem remover os 1ºs arquivos como na função DelSample004.
    Dim FSO As Object
    Dim MyPath As String

    Set FSO = CreateObject("scripting.filesystemobject")

    MyPath = "C:\Users\Ron\Test"  '<< Change

    If Right(MyPath, 1) = "\" Then
        MyPath = Left(MyPath, Len(MyPath) - 1)
    End If

    If FSO.FolderExists(MyPath) = False Then
        MsgBox MyPath & " não existe."

        Exit Sub
    End If

    FSO.deletefolder MyPath

End Sub

Sub Clear_All_Files_And_SubFolders_In_Folder()
' Apaga todos os arquivos nas subpastas.
' Certifique-se de que não haja nenhum arquivo aberto na pasta.
    Dim FSO As Object
    Dim MyPath As String

    Set FSO = CreateObject("scripting.filesystemobject")

    MyPath = "E:\Bernardes\Dashboards\Test"  '<< Change

    If Right(MyPath, 1) = "\" Then
        MyPath = Left(MyPath, Len(MyPath) - 1)
    End If

    If FSO.FolderExists(MyPath) = False Then
        MsgBox MyPath & " não existe."
        Exit Sub
    End If

    On Error Resume Next

    ' Apaga os arquivos.
    FSO.deletefile MyPath & "\*.*", True

    ' Apaga as pastas.
    FSO.deletefolder MyPath & "\*.*", True

    On Error GoTo 0

End Sub

Para impedir que os arquivos sejam excluídos pela instrução Kill, certifique-se de que as declarações de Kill sempre refiram-se a um caminho válido e a um nome de arquivo válido. Os exemplos a seguir demonstram a sintaxe que devemos utilizar:

   Kill "\\server\share\myfiles\*.old"
   Kill "E:\myfiles\*.old"
   Dim FileList As String
   FileList = "*.old"
   Kill "\\server\share\myfiles\" & FileList
   Dim FileList As String, NetPath As String
   NetPath = "\\server\share\myfiles\"
   FileList = "*.old"
   Kill NetPath & FileList
Esses são usos válidos da instrução Kill. 

Tags: VBA, Tips, Ron de Bruin, delete, files, file, folder, kill




VBA Outlook - Inserindo assinatura simples no e-mail como TXT - Insert Outlook Signature in mail


O código nesta página só funciona quando você usa o Outlook como seu programa de email.

Inserindo uma assinatura simples (txt) na mensagem.

Nos dois códigos anteriores (1, 2) usamos a propriedade .HTMLBody para adicionar texto e uma assinatura ao e-mail.

Mas o que podemos usar na propriedade .Body no corpo do e-mai para criar uma mensagem simples?

Teremos 2 opções:

1ª OPÇÃO: MailOutlookWithSignatureHtml01
Altere o conteúdo da variável strbody para:

Let strbody = "Cara Cliente Ana Cláudia" & vbNewLine & vbNewLine & _
            "This is line 1" & vbNewLine & _
            "This is line 2" & vbNewLine & _
            "This is line 3" & vbNewLine & _
            "This is line 4"

Altere a linha .HTMLBody para:

Let .Body = strbody & vbNewLine & .Body


2ª OPÇÃO: MailOutlookWithSignatureHtml02
Altere o conteúdo da linha strbody para:

Let strbody = "Cara Cliente Ana Cláudia" & vbNewLine & vbNewLine & _
            "This is line 1" & vbNewLine & _
            "This is line 2" & vbNewLine & _
            "This is line 3" & vbNewLine & _
            "This is line 4"

Altere a linha .HTMLBody para:

     Let .Body = strbody & vbNewLine & Signature

Mude também a extensão (htm) do arquivo de assinatura MySig.htm na SigString para txt.


ReferênciaRon de Bruin 

Tags: VBA, Outlook, email, e-mail, send, enviar, assinatura, signature, HTM, RTF, TXT, Ron de Bruin


diHITT - Notícias