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.

.: Vitrine

Carregando artigos...

Views

Mostrando postagens com marcador folder. Mostrar todas as postagens
Mostrando postagens com marcador folder. Mostrar todas as postagens

VBA Excel - Função DIR - 01 - Percorrer os arquivos em uma pasta - Loop Through the Files in a Folder


No VBA do Microsoft Excel, a função Dir é usada para retornar o primeiro nome do arquivo num diretório especificado, e uma lista dos seus atributos.

O nome do arquivo é retornado como uma String. A função Dir pode ser usada sem os respectivos argumentos para retornar o nome do próximo arquivo, neste mesmo diretório.

O uso mais comum da função Dir é percorrer todos os arquivos de uma pasta, executando uma ação em cada um. Outros usos comuns incluem a verificação da existência destes, saber se um diretório existe, ou procurar um arquivo específico.


Percorrer os arquivos em uma pasta

Sub AllFiles()

Dim MyFolder As String 'Path containing the files for looping
Dim MyFile As String 'Filename obtained by Dir function
Let MyFolder = "C:\ExcelFiles" 'Assign directory to MyFolder variable

Let MyFile = Dir (MyFolder) 'Dir gets the first file of the folder

'Loop through all files until Dir cannot find anymore
Do While MyFile <> ""

    The statements you want to run on each file
   
    Let MyFile = Dir 'Dir gets the next file in the folder

Loop

End Sub



brazilsalesforceeffectiveness@gmail.com

✔ Brazil SFE®Author´s Profile  Google+   Author´s Professional Profile   Pinterest   Author´s Tweets

VBA Excel - Função DIR - 02 - Listar os arquivos de uma pasta em uma planilha - List the Files from a Folder on a Worksheet




No VBA do Microsoft Excel, a função Dir é usada para retornar o primeiro nome do arquivo num diretório especificado, e uma lista dos seus atributos.

O nome do arquivo é retornado como uma String. A função Dir pode ser usada sem os respectivos argumentos para retornar o nome do próximo arquivo, neste mesmo diretório.

O uso mais comum da função Dir é percorrer todos os arquivos de uma pasta, executando uma ação em cada um. Outros usos comuns incluem a verificação da existência destes, saber se um diretório existe, ou procurar um arquivo específico.


Listar os arquivos de uma pasta em uma planilha

Sub ListFiles()

Dim MyDirectory As String 'Folder containing the files
Dim MyFile As String 'The filename to enter on the worksheet
Dim NextRow As Long 'The row for the next filename in list

MyDirectory = "C:\ExcelFiles" 'Assign directory to MyDirectory variable

MyFile = Dir(MyDirectory) 'Dir gets the first file in the folder

'Find the next empty row in the list and store in NextRow variable
NextRow = Application.CountA(Range("A:A")) + 1

Do Until MyFile = ""

      Cells(NextRow, 1).value = MyFile
     
      NextRow = NextRow + 1 'Move to the next row

      MyFile = Dir 'Dir gets the name of next file in the folder
Loop

End Sub



brazilsalesforceeffectiveness@gmail.com

✔ Brazil SFE®Author´s Profile  Google+   Author´s Professional Profile   Pinterest   Author´s Tweets

VBA Excel - Função DIR - 03 - Verificando a existência de um Arquivo - Check if a Files Exists



No VBA do Microsoft Excel, a função Dir é usada para retornar o primeiro nome do arquivo num diretório especificado, e uma lista dos seus atributos.

O nome do arquivo é retornado como uma String. A função Dir pode ser usada sem os respectivos argumentos para retornar o nome do próximo arquivo, neste mesmo diretório.

O uso mais comum da função Dir é percorrer todos os arquivos de uma pasta, executando uma ação em cada um. Outros usos comuns incluem a verificação da existência destes, saber se um diretório existe, ou procurar um arquivo específico.


Verificando a existência de um Arquivo

Sub FileExists()

      Dim TheFolder As string 'Location of the file
      Dim FiletoCheck As String 'Name of the file you want to check

TheFolder = "C:\ExcelFiles" 'Assign directory to TheFolder variable

'Capture the name of file to check for using an input box
FiletoCheck = InputBox("Enter the name of the file you want to look for", "Enter file name")

'If FiletoCheck is an empty string then file not found
If FiletoCheck = "" Then
     
      Msgbox "Oh no, the file does not exist"

Else

      Msgbox "Yes, the file exists."

End If

End Sub



Tags: Excel, VBA, Files, Folder, list, Dir, filedatetime, xls, xlsm, xlsb, arquivos, pasta, check, exists, function, directory, 

Inline image 1

Excel VBA - Liste todas as Planilhas na Pasta - List All the Excel Files in a folder







Também podemos recuperar algumas informações destes arquivos se necessário. Este código VBA listará os nomes e data da última atualização.



Como isso funciona?

A caixa de diálogo de seleção de pasta é usada para tornar mais fácil para o usuário selecionar o local desejado, retornando os arquivos.

A função Dir será usada para retornar cada nome de arquivo da pasta ou diretório.

Este código retornará listando todos os arquivos Excel contidos na pasta. Especificamos isso ao usar *. XLS na função Dir. O curinga e a extensão podem ser alterados para listar todos os arquivos que desejarmos, ou omitir inteiramente alguns arquivos desta.

O método FileDateTime foi usado para capturar a data de criação ou modificação.


Sub ImportFileList()
Dim MyFolder As String 'Store the folder selected by the using
Dim FiletoList As String 'store the name of the file ready for listing
Dim NextRow As Long 'Store the row to write the filename to

On Error Resume Next

Let Application.ScreenUpdating = False

'Display the folder picker dialog box for user selection of directory
With Application.FileDialog(msoFileDialogFolderPicker)
    Let .Title = "Please select a folder"
    .Show
    Let .AllowMultiSelect = False
    If .SelectedItems.Count = 0 Then
        MsgBox "You did not select a folder"
        Exit Sub
    End If
    Let MyFolder = .SelectedItems(1) & "\"
End With

'Dir finds the first Excel workbook in the folder
Let FiletoList = Dir(MyFolder & "*.xls")
Let Range("A1").Value = "Filename"
Let Range("B1").Value = "Date Last Modified"
Let Range("A1:B1").Font.Bold = True

'Find the next empty row in the list
Let NextRow = Application.CountA(Range("A:A")) + 1

'Do whilst the dir function returns an Excel workbook
Do While FiletoList <> ""
    Let Cells(NextRow, 1).Value = FiletoList 'Write the filename into the next available cell
    Let Cells(NextRow, 2).Value = FileDateTime(MyFolder & FiletoList) 'Write the date the cell was last modified
    Let NextRow = NextRow + 1 'Move to next row
    Let FiletoList = Dir 'Dir returns the next Excel workbook in the folder
Loop

Let Application.ScreenUpdating = True

End Sub
















Tags: Excel, VBA, Files, Folder, list, Dir, filedatetime, xls, xlsm, xlsb, 







Inline image 1


VBA Excel - Ajuste o layout de diversas planilhas - Loop through all worksheets in all Excel workbooks in a folder to change the font, font size, and alignment of text in all cells



Gosto muito de automatizar os processos que envolvem a repetição e o retrabalho humano. Isso poupa muito tempo e dinheiro. Gastar tempo automatizando um processo é algo realmente recompensador.

Ao gerarmos diversos relatórios em planilhas diferentes (workbook) do MS Excel, não queremos perder tempo formatando-as durante a geração e processamento de tais dados. Mas podemos programar para que sejam minimamente formatadas depois que tudo terminar e todos os arquivos estiverem gravados em uma pasta do nosso servidor ou estação de trabalho. Como?

Sub FormatLayoutFiles()
    Const fPath As String = "D:\Bernardes\Docs\"

    Dim sh As Worksheet
    Dim sName As String

    With Application
        Let .Calculation = xlCalculationManual
        Let .EnableEvents = False
        Let .ScreenUpdating = False
    End With

    Let sName = Dir(fPath & "*.xls*")

    Do Until sName = ""
        With GetObject(fPath & sName)
            For Each sh In .Worksheets
                With sh
                    Let .Cells.HorizontalAlignment = xlLeft
                    Let .Cells.Font.Name = "Arial"
                    Let .Cells.Font.Size = 10
                End With
            Next sh
            .Close True
        End With

        Let sName = Dir
    Loop

    With Application
        Let .Calculation = xlAutomatic
        Let .EnableEvents = True
        Let .ScreenUpdating = True
    End With
End Sub


Tags: Excel, VBA, format, layout, fomatação, Loop, worksheets, workbooks, folder,change, font, font size, alignment, text, cells


VBA Excel - Copie Arquivos a partir das suas Datas - Copy all files between certain dates

Inline image 7

Imagine poder automatizar a cópia de arquivos de uma pasta de acordo com a respectiva data da sua gravação.

Esse processo seria muito significativo no que diz respeito a backup dentro de um processo batch.

Também seria proveitoso dentro de um processo onde arquivos texto precisassem ser movidos temporariamente, dentro de um intervalo mensal ou semanal, para uma pasta onde seriam processados e posteriormente deletados.

O exemplo abaixo nos propicia tal liberdade, e nos dá a liberdade de adequá-lo melhor, dentro das nossas necessidades.

Sempre é preciso ter cautela, pois no caso do código abaixo, há a possibilidade de sobrepormos arquivos.

Sub CopyFilesInDates()
    Dim FSO As Object
    Dim FromPath As String
    Dim ToPath As String
    Dim Fdate As Date
    Dim FileInFromFolder As Object 

    FromPath = "C:\Bernardes\Data"  
    ToPath = "C:\Bernardes\Process"     

    If Right(FromPath, 1) <> "\" Then 
        FromPath = FromPath & "\" 
    End If 

    If Right(ToPath, 1) <> "\" Then 
        ToPath = ToPath & "\" 
    End If 

    Set FSO = CreateObject("scripting.filesystemobject") 

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

    If FSO.FolderExists(ToPath) = False Then
        MsgBox ToPath & " doesn't exist"
        Exit Sub
    End If 

    For Each FileInFromFolder In FSO.getfolder(FromPath).Files
        Fdate = Int(FileInFromFolder.DateLastModified)
        'Copy files from 1-Oct-2006 to 1-Nov-2006
        If Fdate >= DateSerial(2006, 10, 1) And Fdate <= DateSerial(2006, 11, 1) Then
            FileInFromFolder.Copy ToPath
        End If
    Next FileInFromFolder 
    MsgBox "Você encontrará os seus arquivos daqui " & FromPath & ", aqui " & ToPath

End Sub

Tags: VBA, Excel, folder, file, pasta, arquivo, copia, planilha, Por data, 






diHITT - Notícias