Dir vba excel примеры

Функция Dir служит для проверки существования каталога или файла, отвечающих заданному образцу.

Функция поддерживает использование подстановочных знаков для нескольких символов (*) и одиночного символа (?) для указания нескольких файлов. Функция возвращает первое имя файла, имя которого соответствует аргументу PathName. Для получения остальных файлов, имена которых соответствуют PathName, следует повторно вызвать функцию Dir без аргументов. Последовательные вызовы функции без аргументов возможны до тех пор, пока имеются файлы или папки, соответствующие образцу первого вызова (с аргументами)
Примечание Рекурсивные вызовы функции Dir запрещены

Синтаксис функции в VBA:

Dir[ (PathName[, Attributes])]

Функция возвращает данные типа String, структурно представляющего имя файла или папки, которые удовлетворяют указанному шаблону имени файла, набору атрибутов файла или метке тома на диске. Если аргумент PathName не найден, то функция Dir возвращает пустую строку (““)
Примечание Если после возврата функцией пустой строки, снова вызвать функцию без аргументов, то возникает ошибка времени исполнения Invalid procedure call or argument

Параметры функции

PathName — Необязательный аргумент. Строковое выражение, указывающее имя файла. Также может содержать имя каталога или папки и диска. При использовании имен файлов или папок, содержащих пробелы следует использовать дополнительные кавычки —Dir (» «C:Русский Проектapp.exe“») или Dir (Chr (34) & «C:Русский Проектapp.exe» & Chr (34))
Примечание Хотя PathName указан, как необязательный аргумент, он обязателен при первом вызове функции, а также в случаях, если задан аргумент Attributes

Attributes — Необязательный аргумент, содержащее константу или числовое выражение, описывающее атрибуты файла. Если этот аргумент опущен, возвращаются все файлы, имена которых удовлетворяют содержимому аргумента PathName.

Допустимые значения Attributes

vbNormal=0 — Обычное состояние файла. Используется по умолчанию

vbReadOnly=1  — Атрибут только для чтения

vbHidden=2 — Скрытый атрибут

vbSystem=4  — Системный атрибут

vbVolume=8 — Метка тома

vbDirectory=16 — Каталог или папка

Примечание Можно также указывать комбинации атрибутов путем их суммирования
Например, vbHidden+vbDirectory выводит скрытые папки

Пример кода на языке программирования VBA (Visual Basic for Applications):

' Примеры использования функции

Dim retval

' При наличии выводит WIN.INI

retval=Dir ( «c:windowswin.ini»)

Print retval

' Возвращает имя файла с расширением txt

' При наличии нескольких файлов возвращается

' первый найденный файл

retval = Dir ( «c:windows*.txt»)

MsgBox retval

Возможно вам это будет интересно!

В этом учебном материале вы узнаете, как использовать Excel функцию DIR с синтаксисом и примерами.

Описание

Microsoft Excel функция DIR возвращает первое имя файла, которое соответствует указанному пути и атрибутам. Чтобы получить дополнительные имена файлов, которые соответствуют имени пути и атрибутам, вызовите DIR еще раз без аргументов.
Функция DIR — это встроенная в Excel функция, которая относится к категории функций файлов/каталогов. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.

Синтаксис

Синтаксис функции DIR в Microsoft Excel:

Dir [( path [, attributes ])]

Аргументы или параметры

path
Необязательно. Это путь к файлу, папке или каталогу.
Если path не найден, функция DIR вернет строку нулевой длины.
attributes
Необязательно. Это сумма атрибутов файла. Атрибуты файла могут быть одним из следующих значений или их комбинацией:

Константа VB Значение Пояснение
vbNormal 0 Нормальный (по умолчанию )
vbReadOnly 1 Только для чтения
vbHidden 2 Скрытый
vbSystem 4 Системный файл
vbVolume 8 Метка тома
vbDirectory 16 Каталог или папка
vbAlias ​​ 64 Имя файла является псевдонимом

Примечание

Вы можете использовать подстановочные знаки для указания нескольких файлов. Вы можете выбрать следующие шаблоны:

Подстановочный символ Пояснение
* Позволяет сопоставить любую строку любой длины (включая нулевую)
? Позволяет сопоставить один символ

Возвращаемое значение

Функция DIR возвращает строковое значение.

Применение

  • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Тип функции

  • Функция VBA

Пример (как функция VBA)

Функция DIR может использоваться только в коде VBA в Microsoft Excel.
Рассмотрим несколько примеров функции Excel DIR, чтобы понять, как использовать Excel функцию DIR в коде Excel VBA:

Dir(«C:tracert.txt»)

Результат: «tracert.txt»

Dir(«C:tr*.txt»)

Результат: «tracert.txt»

Dir(«C:tracer?.txt»)

Результат: «tracert.txt»

Например:

Dim LResult As String

LResult = Dir(«C:tracert.txt»)

В этом примере переменная с именем LResult теперь будет содержать имя файла tracert.txt.

Часто задаваемые вопросы

Вопрос: Как я могу использовать функцию DIR, чтобы проверить, существует ли файл?
Ответ: Это может выполняется с помощью формулы, в которой используется комбинация функций DIR, IF и LEN, например:

If Len(Dir(«c:Instructions.doc»)) = 0 Then

  Msgbox «Этот файл НЕ существует.»

Else

  Msgbox «Этот файл существует.»

End If

Вопрос: Я не уверен, существует ли уже конкретный каталог.
Если его не существует, я бы хотел создать его с помощью кода VBA. Как я могу это сделать?

Ответ: Вы можете проверить, существует ли каталог, используя приведенный ниже код VBA:

If Len(Dir(«c:alexExcelExamples», vbDirectory)) = 0 Then

   MkDir «c:alexExcelExamples»

End If

В этом примере код сначала проверяет, существует ли каталог c:alexExcelExamples.
Если он не существует, то оператор MKDIR создаст новый каталог с именем Examples в каталоге c:alexExcel.

DIR is a very special function in VBA, its job is to return a string representing the name of a file, directory, or archive that matches a specified pattern. DIR function only returns the first file name or folder name from a location that matches the specified attributes.

To fetch other file names or folder names from that location that match previously specified attributes, you need to call the DIR Function again with no arguments. This property of DIR Function can be quite useful in iterating or enlisting files or directories present inside a location.

Please note that the DIR function can just give you the name of the file. But if you also need attributes of a file (like last modified date, size, etc.) then consider using FileObjectSystem.

VBA DIR Example

Syntax of VBA DIR Function:

The syntax of DIR is as follows:

DIR(pathname, attributes)

Here, ‘pathname’ specifies the location of a file, folder, or directory. If the ‘pathname’ is not found, DIR returns a string of zero length.

attributes’ is an optional argument. It can be anyone or summation of the following values:

Attribute Name Description
vbNormal Normal (Default). Specifies files with no attributes.
vbReadOnly Specifies read-only files as well as files with no attributes.
vbHidden Specifies hidden files as well as files with no attributes.
vbSystem Specifies System files as well as files with no attributes.
vbVolume Specifies volume label; If you use any other attribute with this one then, the volume label is ignored.
vbDirectory Specifies Directories or Folders.
vbArchive Specifies Archives or Backup Files.
vbAlias Specifies Files having different names.

Few Important points about VBA DIR Function

  • Both the arguments in DIR Function are optional.
  • You can use the wildcard character (like: ‘?’ or ‘*’) with DIR to specify multiple files.
    • ‘*’ allows you to match any string of any length (including zero-length)
    • ‘?’ allows you to match any single character.
  • You must call the DIR Function along with the ‘pathname’ parameter for the first time. Subsequent calls to DIR Function can be made with no arguments to retrieve the next item.

5 Beginner Level Examples of DIR Function in VBA

Example 1: Supplying a file path to DIR Function

  • Dir("C:SomeFile.txt") would return SomeFile.txt
  • Dir("C:Some*.txt") would return SomeFile.txt (Provided there is no other file that starts with the word “Some”)
  • Dir("C:SomeFil?.txt") would return SomeFile.txt

Example 2: Write a VBA code to retrieve the first .exe file from the Windows folder.

You can use the below code to do this:

Sub RetrieveFile()
File = Dir("C:Windows*.exe")
MsgBox File
End Sub

Explanation: This code retrieves the .exe file from the Windows folder and displays its name in a message box. If there are multiple .exe files inside the Windows Folder then this code will retrieve only the first one.

 Example 3: Use DIR Function to check if a File exists or not.

Below is the code to check this:

Sub RetrieveFile()
File = Dir("C:WindowsCSUP.txt")
If Len(File) > 0 Then
MsgBox (File & " Exists")
Else
MsgBox ("File Doesn't Exists")
End If
End Sub

Explanation: In this code, we have supplied the filename to the DIR Function. If DIR returns a string whose length is greater than 0 that means “File Exists”. We have checked this by using an IF Function.

Example 4: Write a VBA Code to check if a directory is present or not. If the directory is not present then create that directory.

To accomplish this we can use the below code:

Sub RetriveFolder()
MyFolder = "C:TestDirectory"
Fldr = Dir(MyFolder, vbDirectory)
If Len(Fldr) > 0 Then
MsgBox (Fldr & " Already Exists")
Else
MkDir MyFolder
MsgBox ("Folder Created")
End If
End Sub

Explanation: In this code, we have supplied the folder path to the DIR Function. If DIR returns a string whose length is greater than 0 that means “Folder Exists” otherwise that Folder will be created.

Example 5: The Folder “C:Test” contains all hidden files. Write a VBA Code to retrieve the name of the first hidden file.

Sub RetrieveFile()
MyFile = Dir("C:Test*.*", vbHidden)
MsgBox MyFile
End Sub

Explanation: In this code, the DIR function will search the files with hidden attribute inside the “C:Test” folder. If this folder contains multiple hidden files then, DIR will return the first hidden file.

3 Advanced Level Examples of DIR Function in Excel

Example 6: Create a VBA code that can iterate through all the folders inside a path (immediate child folders only).

To do this we can use the following code:

Sub Iterate_Folders()
Dim ctr As Integer
ctr = 1
Path = "C:Windows " ' Path should always contain a '' at end
FirstDir = Dir(Path, vbDirectory) ' Retrieving the first entry.
Do Until FirstDir = "" ' Start the loop.
If (GetAttr(Path & FirstDir) And vbDirectory) = vbDirectory Then
ActiveSheet.Cells(ctr, 1).Value = Path & FirstDir
ctr = ctr + 1
End If
FirstDir = Dir() ' Getting next entry.
Loop
End Sub

Explanation: In this code, we have used a Do Until Loop and DIR Function to iterate through all the folders present inside a location. It writes the result in the “A:A” range of the active sheet.

Notice that we have used DIR Function twice in this code, the first time with two arguments and the second time with no arguments to fetch the subsequent files.

Example 7: Create a VBA code that can iterate through all the files present at a location. (No need to list files under subfolders)

You can use the below code to accomplish this:

Sub Iterate_Files()
Dim ctr As Integer
ctr = 1
Path = "C:Windows " ' Path should always contain a '' at end
File = Dir(Path) ' Retrieving the first entry.
Do Until File = "" ' Start the loop.
ActiveSheet.Cells(ctr, 1).Value = Path & File
ctr = ctr + 1
File = Dir() ' Getting next entry.
Loop
End Sub

Explanation: In this code, we have used a looping statement along with DIR Function to iterate through all the files present inside a location. It writes the result in “A:A” range of active sheet.

Example 8: Use the concept of the above two examples and write a VBA code that enlists all the files inside a current location and its subfolder.

For this example you can use the following code:

Sub Retrieve_File_listing()
Worksheets(1).Cells(2, 1).Activate
Call Enlist_Directories("C:UsersAnkitDesktopExcelTrick ", 1)
End Sub
Public Sub Enlist_Directories(strPath As String, lngSheet As Long)
Dim strFldrList() As String
Dim lngArrayMax, x As Long
lngArrayMax = 0
strFn = Dir(strPath & "*.*", 23)
While strFn <> ""
If strFn <> "." And strFn <> ".." Then
If (GetAttr(strPath & strFn) And vbDirectory) = vbDirectory Then
lngArrayMax = lngArrayMax + 1
ReDim Preserve strFldrList(lngArrayMax)
strFldrList(lngArrayMax) = strPath & strFn & ""
Else
ActiveCell.Value = strPath & strFn
Worksheets(lngSheet).Cells(ActiveCell.Row + 1, 1).Activate
End If
End If
strFn = Dir()
Wend
If lngArrayMax <> 0 Then
For x = 1 To lngArrayMax
Call Enlist_Directories(strFldrList(x), lngSheet)
Next
End If
End Sub

Explanation: This code first iterates through all the folders present inside a location and stores them in an array. Later it recursively calls the ‘Enlist_Directories’ function to retrieve the file names.

So, this was all about VBA DIR Function in Excel.

Return to VBA Code Examples

Dir Description

Returns the first filename that matches the pathname and attributes specified.

Simple Dir Examples

MsgBox Dir("")

This will return the first file name on the current path.

Dir Syntax

In the VBA Editor, you can type  “Dir(” to see the syntax for the Dir Function:

The Dir function contains 2 arguments:

PathName: [Optional] A string expression representing a directory/folder/drive.

Attribute: [Optional] Specifies file attributes. If omitted, returns files that match pathname but have no attributes.

The Attribute argument settings are:

Constant Value Description
vbNormal 0 (Default) Specifies files with no attributes.
vbReadOnly 1 Specifies read-only files in addition to files with no attributes.
vbHidden 2 Specifies hidden files in addition to files with no attributes.
vbSystem 4 Specifies system files in addition to files with no attributes. Not available on the Macintosh.
vbVolume 8 Specifies volume label; if any other attribute is specified, vbVolume is ignored. Not available on the Macintosh.
vbDirectory 16 Specifies directories or folders in addition to files with no attributes.
vbAlias 64 Specified file name is an alias. Available only on the Macintosh.

Examples of Excel VBA Dir Function

To list the folders&files on C drive, you can use the following code.

Sub Dir_Example()
    Dim fileName    As String
    Dim fullName    As String
    Dim rng         As Range
    Dim i           As Integer

    Set rng = Range("A1")
    
    fileName = Dir("C:", vbDirectory)
    i = 1
    
    Do
        fullName = "C:" & fileName
        rng.Offset(i, 0) = fileName
        rng.Offset(i, 1) = FileDateTime(fullName)
        rng.Offset(i, 2) = FileLen(fullName)
        rng.Offset(i, 3) = GetAttr(fullName)
        
        
        fileName = Dir
        If fileName = "" Then Exit Do
        i = i + 1
    Loop
End Sub

The result will be similar with the following.

VBA Dir Function in Access VBA

The VBA Dir function works in Access VBA in the same way as it does in Excel VBA.

Function CreateDirectory(strP As String) As Boolean
   If Len(Dir(strP, vbDirectory)) = 0 Then
      MkDir strP
   End If
   CreateDirectory = True
   Exit Function
ending:
   CreateDirectory = False
End Function

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

VBA has some useful functions that can take your automation in Excel to the next level.

One such function is the VBA DIR function.

While by itself, it may seem like a simple function that does one specific thing.

But when you combine it with some other useful elements of the VBA coding language, you can create powerful stuff (covered in the examples later in this tutorial).

What Does VBA Dir Function Do?

Use VBA DIR function when you want to get the name of the file or a folder, using their path name.

To give you an example, if you have an Excel file in a folder, you can use the VBA DIR function to get the name of that Excel file (or any other type of file).

What if I want to get the names of all the Excel files in the folder (or all the files – be it Excel file or not)?

You can do that too!

When you use DIR function once, it returns the first file name in a folder. Now if you want to get the names of the second, third, fourth files as well, you can use the DIR function again (covered later as an example).

Dir returns the first file name that matches the pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string (“”). Covered in Example 3 and 4 later in this tutorial.

Syntax of VBA DIR Function

Dir [ (pathname [ ,attributes ] ) ]
  • pathname: This is an optional argument. This can be the file name, folder name, or directory name. If pathname is not found, VBA DIR function returns a zero-length string (“”)
  • attributes: This is an optional argument. You can use this argument to specify some attributes and DIR function will return the file names based on those attributes. For example, if you want a list of all hidden files or read-only files (along with files with no attributes), you need to specify that in this argument.

Attributes available to use in VBA DIR function (you can use one or more of these):

Constant Value Description
vbNormal 0 (Default) Specifies files with no attributes.
vbReadOnly 1 Specifies read-only files in addition to files with no attributes.
vbHidden 2 Specifies hidden files in addition to files with no attributes.
VbSystem 4 Specifies system files in addition to files with no attributes. Not available on the Macintosh.
vbVolume 8 Specifies volume label; if any other attributed is specified, vbVolume is ignored. Not available on the Macintosh.
vbDirectory 16 Specifies directories or folders in addition to files with no attributes.
vbAlias 64 Specified file name is an alias. Available only on the Macintosh.

Using Wildcard Characters with DIR Function

If you’re working with Windows, you can also use the wildcard characters in the DIR function.

Note that you can not use these when working with VBA in Macintosh.

Using wildcards can be useful when:

  • You want to get the file names of a particular file type (such as .XLSX or .PPTX)
  • When you have a specific suffix/prefix in filenames and you want to get the names of these files/folders/directories. For example, if you want the names of all the files with the prefix 2019 in it, you can do that using wildcard characters.

There are three wildcard characters in Excel:

  1. * (asterisk) – It represents any number of characters. For example, 2019* would give you the names of all the files with the prefix 2019 in it.
  2. ? (question mark) – It represents one single character. For example, 2019? would give you the names of all the files that start with 2019 and has one more character in the name (such as 2019A, 2019B, 2019C, and so on)

Note: There is one more wildcard character – tilde (~). Since it’s not used a lot, I have skipped its explanation. You can read more about it here if interested.

VBA DIR Function – Examples

Now let’s dive in and see some examples of using the VBA DIR function.

Example 1 – Getting the File Name from its Path

When you have the path of a file, you can use the DIR function to get the name of the file from it.

For example, the below code returns the name of the file and shows it in a message box.

Sub GetFileNames()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTestExcel File A.xlsx")
MsgBox FileName
End Sub

The above code uses a variable ‘FileName’ to store the file name that is returned by the DIR function. It then uses a message box to display the file name (as shown below).

File Name using VBA DIR Function

And what happens when the file doesn’t exist?

In that case, the DIR function would return an empty string.

The below code uses an If Then Else statement to check whether the file exists or not. If the file doesn’t exist, it shows a message box with a text “File Doesn’t Exist”, else it shows the file name.

Sub CheckFileExistence()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTestExcel File A.xlsx")

If FileName <> "" Then
    MsgBox FileName
Else
    MsgBox "File Doesn't Exist"
End If

End Sub

Example 2 – Check if a Directory Exists or Not (and create if it doesn’t)

The below code checks whether the folder ‘Test’ exists or not.

A message box is used to show a message in case the folder exists or when it doesn’t exist.

Sub CheckDirectory()
Dim PathName As String
Dim CheckDir As String

PathName = "C:UserssumitDesktopTest"
CheckDir = Dir(PathName, vbDirectory)

If CheckDir <> "" Then
    MsgBox CheckDir & " exists"
Else
    MsgBox "The directory doesn't exist"
End If

End Sub

You can refine this code further to check whether the folder exists or not, and if it doesn’t, then you can use VBA to create that folder.

Below is the code that uses the MkDir function to create a folder in case it doesn’t exist.

Sub CreateDirectory()
Dim PathName As String
Dim CheckDir As String

PathName = "C:UserssumitDesktopTest"
CheckDir = Dir(PathName, vbDirectory)

If CheckDir <> "" Then
    MsgBox CheckDir & " folder exists"
Else
    MkDir PathName
    MsgBox "A folder has been created with the name" & CheckDir
End If

End Sub

Example 3 – Get the Names of All File and Folders in a Directory

If you want to get a list of all the file and folder names in a directory, you can use the DIR Function.

The below code lists all the files and folder names in the Test folder (which is located at the following path – C:UserssumitDesktopTest).

I am using Debug.Print to show the names in the Immediate window. You can also use this to list the names in a message box or in a column in Excel.

Sub GetAllFile&FolderNames()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTest", vbDirectory)

Do While FileName <> ""
    Debug.Print FileName
    FileName = Dir()
Loop
End Sub

The Do While loop in the above code continues till all the files and folders in the given path have been covered. When there are no more files/folders to cover, FileName becomes a null string and the loop stops.

Example 4 – Get the Names of All Files in a Folder

You can use the below code to get the names of all the files in a folder/directory (and not the names of the sub-folders).

Sub GetAllFileNames()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTest")

Do While FileName <> ""
    Debug.Print FileName
    FileName = Dir()
Loop
End Sub

This code is just like the code used in Example 3, with one minor difference.

In this code, I have not specified vbDirectory in the DIR function. When you specify vbDirectory, it will give you the names of all the files as well as folders.

When you don’t specify vbDirectory, DIR function will only give you the names of the files.

Note: If you want to get the names of all the files in the main folder and the sub-folders, you can’t use the DIR function (as it’s not recursive). To do this, you can either use Power Query (no coding needed) or use the File System Object in VBA (with recursion).

Example 5 – Get the Names of All the Sub-Folders within a Folder

The below code would give you the names of all the sub-folders within the specified folder.

It uses the GetAtr function in VBA, which allows us to check whether the name returned by the DIR function is the name of a file or a folder/directory.

Sub GetSubFolderNames()
Dim FileName As String
Dim PathName As String

PathName = "C:UserssumitDesktopTest"
FileName = Dir(PathName, vbDirectory)

Do While FileName <> ""
If GetAttr(PathName & FileName) = vbDirectory Then
    Debug.Print FileName
End If
FileName = Dir()
Loop
End Sub

Again, I am using Debug.Print to get the names in the immediate window. You can get these in a message box or in Excel (by modifying the code accordingly).

Example 6 – Get the First Excel File from a Folder

With DIR function, you can specify the file extension or any suffix/prefix that you want in the file name that is returned.

The below code would display the name of the first Excel file in the Test folder.

Sub GetFirstExcelFileName()
Dim FileName As String
Dim PathName As String

PathName = "C:UserssumitDesktopTest"
FileName = Dir(PathName & "*.xls*")
MsgBox FileName
End Sub

Note that I have used *.xls* (asterisk sign on both sides). This will ensure that all the versions of Excel files are checked (.xls, xlsx, .xlsm, .xlsb).

Example 7 – Get Names of All Excel File in a Folder

Use the below code to get the names of all the Excel files in the Test folder.

Sub GetAllFileNames()
Dim FolderName As String
Dim FileName As String
FolderName = "C:UserssumitDesktopTest"
FileName = Dir(FolderName & "*.xls*")

Do While FileName <> ""
    Debug.Print FileName
    FileName = Dir()
Loop

End Sub

While the DIR function returns the name of the first Excel file only, since we are calling it again in the loop, it goes through all the files and gives us the names of all the Excel files.

Hope you found this tutorial and the examples useful.

Let me know your thoughts in the comments section.

You May Also Like the Following Excel Tutorials:

  • Excel VBA InStr Function.
  • Excel VBA Split Function.
  • Excel VBA TRIM Function
  • VBA LCASE Function.
  • VBA UCASE Function.

VBA Dir function in Excel is categorized as File and Directory function. This built-in VBA Dir function returns the first name of a file or directory that matches a pattern in Excel VBA.The VBA Dir function is specifically useful for listing all files located in a specified directory.

This function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA Dir Function in any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the Dir function, where we can use this Dir Function and real-time examples in Excel VBA.

Table of Contents:

  • Overview
  • Syntax of VBA Dir Function
  • Parameters or Arguments
  • Where we can apply or use VBA Dir Function?
  • Example 1: Check whether file exists or not?
  • Example 2: List all .xls Files in a Folder using Wild card character(*)
  • Example 3: List all Files in a Folder using Wild card character(?)
  • Example 4: List all files in a ‘C’ Directory using File Attribute(vbDirectory)
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the Dir Function in VBA is

Dir([PathName],[Attribute])

Note: The Dir Function returns a string value.

Parameters or Arguments:

The Dir function has two arguments in Excel VBA.
where
PathName: It is an optional parameter. The PathName argument represents a file, folder or directory. If specified path is not available, then DIR function will return a zero-length string.
Attribute: It is an optional parameter. The Attribute represents the file attributes. These file attributes can be one or a combination of the following values.

VBA CONSTANT VALUE DESCRIPTION
vbNormal 0 Normal (Default)
vbReadOnly 1 Read-only
vbHidden 2 Hidden
vbSystem 4 System file
vbVolume 8 Volume label
vbDirectory 16 Directory or folder
vbAlias 64 File name is an alias

Note: We can use wildcard characters, when we want to specify multiple file attributes. We can use either * and ? as wildcard characters.

Wild Card Character Description
* Allows you to match any string of any length (including zero length)
? Allows you to match on a single character

Where we can apply or use VBA Dir Function?

We can use this Dir Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Check whether file exists or not

Here is a simple example of the VBA Dir function. This below example checks whether file exists or not.

'Check whether file exists or not
Sub VBA_Dir_Function_Ex1()

    'Variable declaration
    Dim sPath As String
    Dim sStatus As String
    
    sPath = "C:TempVBAF1String_Functions.xls"
             
    sStatus = Dir(sPath)
    
    If sStatus <> "" Then
        MsgBox "Specified file found.", vbInformation, "VBA Dir Function"
    Else
        MsgBox "Specified file not found.", vbInformation, "VBA Dir Function"
    End If
    
End Sub

Output: Here is the screen shot of the first example output.
VBA Dir Function

Example 2: List all .xls Files in a Folder using Wild card character(*)

Here is a simple example of the VBA Dir function. This below example lists all .xls Files in a folder using Wild card character(*) and returns all available .xls files.

'List all .xls Files in a Folder using Wild card character(*)
Sub VBA_Dir_Function_Ex2()

    'Variable declaration
    Dim sPath As String
    Dim sFile As String, fList As String
    
    sPath = "C:VBAF1VBA FunctionsVBA Text Functions*.xls"
             
    'Read current file
    sFile = Dir(sPath)
       
    'Loop through all files in a directory
    Do While sFile <> ""
        fList = fList & vbCrLf & sFile
        sFile = Dir()
    Loop
        
    MsgBox "List of all .xls files: " & fList, vbInformation, "VBA Dir Function"
       
End Sub

Output: Here is the screen shot of the second example output.
VBA Dir Function

Example 3: List all Files in a Folder using Wild card character(* and ?)

Here is a simple example of the VBA Dir function. This below example lists all .doc Files in a folder using Wild card character(* and ?) and returns all available .doc files.

'List all Files in a Folder using Wild card character(?)
Sub VBA_Dir_Function_Ex3()

    'Variable declaration
    Dim sPath As String
    Dim sFile As String, fList As String
    
    sPath = "C:VBAF1VBA FunctionsVBA Text Functions*.doc?"
             
    'Read current file
    sFile = Dir(sPath)
       
    'Loop through all files in a directory
    Do While sFile <> ""
        fList = fList & vbCrLf & sFile
        sFile = Dir()
    Loop
        
    MsgBox "List of all .xls files: " & fList, vbInformation, "VBA Dir Function"
       
End Sub

Output: Here is the screen shot of the third example output.
VBA Dir Function

Example 4: List all files in a ‘C’ Directory using File Attribute(vbDirectory)

Here is a simple example of the VBA Dir function. This below example lists all available files from ‘C’ Directory. It uses file attribute vbDirectory in the following example.

'List all files in a 'C' Directory using File Attribute(vbDirectory)
Sub VBA_Dir_Function_Ex4()

    'Variable declaration
    Dim sPath As String
    Dim sFile As String, fList As String
    
    sPath = "C:"
             
    'Read current file
    sFile = Dir(sPath, vbDirectory)
       
    'Loop through all files in a directory
    Do While sFile <> ""
        fList = fList & vbCrLf & sFile
        sFile = Dir()
    Loop
        
    MsgBox "List of all files in 'C' Directory: " & fList, vbInformation, "VBA Dir Function"
       
End Sub

Output: Here is the screen shot of the fourth example output.
VBA Dir Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Главная » Функции VBA »

28 Апрель 2011              99025 просмотров

  • CurDir() — функция, которая возвращает путь к каталогу(для указанного диска), в котором по умолчанию будут сохраняться файлы:
        Dim sCurDir As String
        sCurDir = CurDir("D")
  • Dir() — позволяет искать файл или каталог по указанному пути на диске. Пример использования можно посмотреть в статье: Просмотреть все файлы в папке
  • EOF() — при операции записи в файл на диске эта функция вернет True, если вы находитесь в конце файла. Обычно используется при работе с текстовыми файлами — .txt. При сохранении книг Excel лучше использовать стандартные методы: Save и SaveAs.
  • Error() — позволяет вернуть описание ошибки по ее номеру. Генерировать ошибку нужно при помощи метода RaiseError() специального объекта Er.
  • Print — записывает в открытый файл указанный текст. Далее будет приведен пример использования данной функции
  • FreeFile() — позволяет определить номер следующего свободного файла, который можно использовать как номер файла при его открытии методом Open. Предпочтительно применять именно этот метод определения номера файла(вместо статичного #1), чтобы не было неоднозначности обращения к файлам. Ниже приведены примеры применения данной функции при обращении к файлам
  • FileAttr() — позволяет определить, как именно был открыт файл в файловой системе: на чтение, запись, добавление, в двоичном или текстовом режиме и т.п. Применяется для работы с текстовыми файлами, открытыми при помощи Open "C:Text1.txt" For [] As #1
    Открыть файл можно несколькими способами, приведу примеры наиболее распространенных вариантов:

    • Input() — открывает текстовый файл на чтение. Т.е. таким методом можно открыть файл и вытянуть из него данные. Например, чтобы считать информацию из файла C:Text1.txt и вывести ее в окно Immediate можно применить такой код:
          Dim MyChar
          Open "C:Text1.txt" For Input As #1 'Открываем файл функцией Open() на чтение(Input)
          Do While Not EOF(1)  'пока файл не кончился
              ' Получаем по одному символу и добавляем его к предыдущим
              MyChar = MyChar & Input(1, #1)
          Loop
          Close #1 ' Закрываем файл
          'Выводим его содержание в окно Immediate
          '(отобразить Immediate: Ctrl+G в окне редактора VBA)
          Debug.Print MyChar
          'или в MsgBox
          MsgBox MyChar, vbInformation, "www.excel-vba.ru"
    • Ouput() — метод открывает файл для записи. Например, чтобы записать в файл строку, содержащую все ячейки в выделенном диапазоне, можно использовать такой код:
      Sub SelectionToTxt()
          Dim s As String, rc As Range
          Dim ff
          'запоминаем все значения из выделенной строки в строку
          For Each rc In Selection
              If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки
                  s = rc.Value
              Else 'если уже записано - добавляем через TAB
                  s = s & vbTab & rc.Value
              End If
          Next
          ff = FreeFile
          'Открываем текстовый файл
          'если файла нет - он будет создан
          Open "C:Text1.txt" For Output As #ff
          'записываем значение строки в файл
          Print #ff, s
          Close #ff ' Закрываем файл
      End Sub

      Важно помнить, что при открытии файла таким методом(Output) все предыдущие данные из файла стираются и в файле будет записано только то, что мы записали в текущем сеансе. Если данные необходимо добавить к имеющимся — используется метод Append

    • Append() — метод открывает файл для записи, но в отличии от Output записывает данные в конец файла, а не перезаписывает текущие данные. Например, код добавления выделенных ячеек как одной строки в имеющийся файл будет выглядеть так:
      Sub SelectionToTxt_Add()
          Dim s As String, rc As Range
          Dim ff
          'запоминаем все значения из выделенной строки в строку
          For Each rc In Selection
              If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки
                  s = rc.Value
              Else 'если уже записано - добавляем через TAB
                  s = s & vbTab & rc.Value
              End If
          Next
          ff = FreeFile
          'Открываем текстовый файл
          'если файла нет - он будет создан
          Open "C:Text1.txt" For Append As #ff
          'записываем значение строки в файл
          Print #ff, s
          Close #ff ' Закрываем файл
      End Sub
  • FileDateTime() — позволяет получить информацию о последнем времени обращения к указанному файлу. Если к файлу после создания ни разу не обращались, то это будет время создания файла. Если попытаться обратиться к уже открытой книге/файлу — то будет получено время открытия книги/файла, а не создания или сохранения.
        sFileDateTime = FileDateTime("C:Text1.txt")
  • FileLen() — позволяет определить длину указанного файла в байтах:
        MsgBox FileLen("C:Text1.txt") & " bites", vbInformation, "www.excel-vba.ru"
  • GetAttr() — возможность обратиться к файлу к файловой системе и получить информацию об его атрибутах (скрытый, доступен только для чтения, архивный и т.п.)
  • InputB() — позволяет указывать количество байт, которые надо считать из файла. Альтернатива методу Open в случаях, когда необходимо считывать данные не по конкретным строкам, а именно побайтово.
  • Loc() — от Location, то есть местонахождение — возвращает число, которое определяет текущее место вставки или чтения в открытом файле.
  • Seek() — очень похожа на функцию Loc(), но Seek() возвращает информацию о позиции, с которой будет выполняться следующая операция чтения или вставки.
  • LOF() — length of file — позволяет определить длину открытого файла в байтах.

Статья помогла? Сделай твит, поделись ссылкой с друзьями!

The VBA DIR function is also known as the directory function. It is a built-in function in VBA that gives us the file name of a given file or a folder, but we need to provide the path for the file. The output returned by this function is a string as it returns the file’s name. This function has two arguments: the path name and the attributes.

The DIR function returns the first file name in the specified folder path. So, for example, in your D drive, if you have a folder name called 2019. In that folder, if you have an Excel file named “2019 Sales,” you can access this file using the DIR function.

The VBA DIR function is very helpful in getting the file name by using its path folder.

Table of contents
  • Excel VBA DIR Function
    • Syntax
    • Examples to use VBA DIR Function
      • Example #1 – Accessing the File Name using DIR Function
      • Example #2 – Open File by using DIR Function
      • Example #3 – Multiple Open Workbooks using DIR Function
      • Example #4 – Get all the File Names in the Folder
    • Recommended Articles

VBA DIR Function

Syntax

This function has two optional arguments.

VBA Dir Formula

  • [Path Name]: As the name says, what the path to access the file is. It could be the file’s name, the folder’s name, or the directory. It will return an empty string value if any path is not assigned.
  • [Attributes]: This is an optional argument; you may not use this often in coding. You can specify the file’s attribute in the [Path Name], and the DIR function looks for only those files.

For example: If you want to access only hidden files, if you want to access only read-only files, etc., we can specify in this argument. Below are the attributes we can use.

VBA Dir Example 1

Examples to use VBA DIR Function

You can download this VBA Dir Excel Template here – VBA Dir Excel Template

Example #1 – Accessing the File Name using DIR Function

We will explain the simple example of accessing the file name using the DIR function. Follow the below steps.

Step 1: Create a macro name.

Step 2: Define the variable as String.

Code:

Sub Dir_Example1()

  Dim MyFile As String

End Sub

Step 3: Now, we will assign a value using this variable’s DIR function.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir(

End Sub

Step 4: Copy and paste the file folder path on your computer. Mention the pathname in double-quotes.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir("E:VBA Template

End Sub

Step 5: We have mentioned my path to the folder. Now we need to mention the file name and its extension as well. To do this, we first need to put a backslash after the path ().

After entering the backslash, we need to enter the full file name.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir("E:VBA TemplateVBA Dir Excel Template.xlsm")

End Sub

Step 6: Show the value of the variable in the message box.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir("E:VBA TemplateVBA Dir Excel Template.xlsm")

  MsgBox MyFile

End Sub

Now, run the code and see the message box’s result.

VBA Dir Example 1-1

So, the DIR function returned the file name with the file extension.

Example #2 – Open File by using DIR Function

Now, how do we open the file? This function can return the file name, but opening that file is a bit different. Follow the below steps to open the file.

Step 1: Create two variables as String.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

End Sub

Step 2: Now, for the FolderName variable, assign the folder path.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"

End Sub

Step 3: Now, for the FileName variable, we need to get the file name by using the DIR function.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(

End Sub

Step 4: Now, for Path Name, we have already assigned a path to the variable FolderPath, so we can directly supply the variable here.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName

End Sub

Step 5: Now, we need to supply the file name. By using the ampersand symbol (&), assign the file name.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "VBA Dir Excel Template.xlsm")

End Sub

Step 6: Now, use the WORKBOOKS.OPEN method.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "VBA Dir Excel Template.xlsm")

  Workbooks.Open

End Sub

Step 7: File Name is a combination of FolderPath & FileName. So combine these two.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "VBA Dir Excel Template.xlsm")

  Workbooks.Open FolderName & FileName

End Sub

Now, run this code. It will open the mentioned file name.

Open-File Example 2

Example #3 – Multiple Open Workbooks using DIR Function

We can access all the workbooks in the folder. We cannot directly mention all the file names to access every file, but we can use the wildcard character to refer to the file.

The asterisk (*) is one of those wildcard characters. It identifies any number of characters. So, for example, if you want to access all the macro files in the folder, you can use the asterisk as the wildcard, “*.xlsm*.”

Here * will match any file name with the file’s extension equal to “xlsm.”

Code:

Sub Dir_Example3()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "*.xlsm*")

  Do While FileName <> ""
  Workbooks.Open FolderName & FileName
  FileName = Dir()
  Loop

End Sub

Now, the above code will open all the files in the folder path.

FileName = Dir() we have used this line because we have to make the existing file name nil to access the next file in the folder. The moment we make the existing file name nil when the loop runs for the second time, it will take the next file in the folder.

Example #4 – Get all the File Names in the Folder

Suppose you want the list of all the file names in the folder. We can also do this by using attributes.

Code:

Sub Dir_Example4()
  Dim FileName As String
  FileName = Dir("E:VBA Template", vbDirectory)

  Do While FileName <> ""
   Debug.Print FileName
   FileName = Dir()
  Loop
End Sub

Make the immediate window visible by pressing Ctrl + G.

Get all the File Names 1

Now, run the code. We will get all the file names in the immediate window.

Get all the File Names 2

Recommended Articles

This article has been a guide to VBA DIR. Here, we learn how to use the VBA DIR function in excel along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

  • Excel VBA LEN
  • UserForm in VBA
  • How to Code in VBA Excel?
  • On Error in VBA
  • VBA Project Password

Понравилась статья? Поделить с друзьями:
  • Dinosaur meaning of word
  • Dimensions of the word
  • Dim wordapp as word application
  • Dim withevents xlapp as excel application
  • Dim wd as new word application