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 DIR. Mostrar todas as postagens
Mostrando postagens com marcador DIR. 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 Basic - Verifica se o arquivo ou o caminho existem



Esta função VBA (UDF - User Defined Function) testa se um arquivo (file) ou um caminho (path) existem ou se são válidos. 

Se desejar utilizar esta função para testar um caminho, precisará obrigatoriamente colocar "\" como último caracter do Path.


Function Check()
    Dim nFrase As String
    

    Let nFrase = "c:\Bernardes\Dashboard.xlsb"

    If DeepCheck (nFrase) Then

        MsgBox "O caminho e/ou arquivo '" & nFrase & "' existe é válido." _
          , vbInformation _
          , "Informação"

    Else

        MsgBox "O caminho e/ou arquivo '" & nFrase & "' é inválido ou não existe." _
          , vbCritical _
          , "Erro"

    End If
End Sub

Function DeepCheck (nPath As String) As Boolean    
    If Dir (nPath) = vbNullString Then
        Let DeepCheck = False
    Else
        Let DeepCheck = True
    End If    
End Function


Abaixo observamos um código simples que lista todos os arquivos de um determinado diretório.


Está configurado para usar a função Dir para obter as informações sobre onde arquivos estão armazenados na pasta / diretório. Em seguida, simplesmente grava os dados da planilha. É possível utilizar os dados em uma matriz se desejar modificar e usá-lo em outro aplicativo da suíte MS Office. Esta é uma função boa quando precisa gravar um arquivo ou realizar uma operação em todos os arquivos armazenados numa determinada pasta, mas não sabe exatamente como os arquivos são chamados ou quantos são. 


Divirta-se!



Sub ListFilesInDirectory()



Range("A5:A2000").ClearContents



Dim ListFilesInDirectory (10000, 1)

Dim One_File_List   As String

Dim Number_Of_Files_In_Directory As Long



Let One_File_List = Dir$ ("C:" + "\*.*")



Do While One_File_List <> ""

    Let ListFilesInDirectory (Number_Of_Files_In_Directory, 0) = One_File_List

    Let One_File_List = Dir$

    Let Number_Of_Files_In_Directory = Number_Of_Files_In_Directory + 1

Loop



Let Number_Of_Files_In_Directory = 0



While List_Files_In_Directory(Number_Of_Files_In_Directory, 0) <> tom


    Let Range("A5").Offset(Number_Of_Files_In_Directory, 0).Value = ListFilesInDirectory (Number_Of_Files_In_Directory, 0)


    Let Number_Of_Files_In_Directory = Number_Of_Files_In_Directory + 1

Wend



End Sub

Tags: VBA, UDF, user, defined, function, path, file, exist, Dir, directory, files


diHITT - Notícias