Excel vba dir
VBA DIR Function – How to Use in Excel
DIR is a very special function in VBA, its job is to return a string representing the name of a file, directory, or an 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 which 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 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.
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 a 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 following values:
Few Important points about VBA DIR Function:
- Both the arguments in DIR Function are optional.
- You can use 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 Windows folder.
You can use the below code to do this:
Explanation: This code retrieves the .exe file from 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:
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:
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.
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 though all the folders inside a path (immediate child folders only).
To do this we can use following code:
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, first time with two arguments and second time with no arguments to fetch the subsequent files.
Example 7: Create a VBA code that can iterate though all the files present at a location. (No need to list files under subfolders)
You can use the below code to accomplish this:
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:
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.
Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend (his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you guys into ‘Excel Geeks’.
Что означают точки в Dir при использовании атрибута vbDirectory?
вернёт сначала точку, а затем две точки.
Как понять эти точки и где их можно использовать?
Допустим, я получил точку, и что я могу сделать с точкой?
Или, допустим, я получил две точки и что можно сделать с этими точками?
Я так понимаю, что это связано со старыми компьютерами, когда не было Windows и использовалась другая операционная система, и, видимо, с тех пор осталось в использовании. Поэтому тем, кто сразу стал работать на новых компьютерах, не понятны такие детали.
У меня такое предположение, где можно использовать эти точки, — с помощью точек можно определить, является ли папка корневой (под корневой папкой, например, понимается диск «C»). Если эта команда не возвращает точку, значит это корневая папка:
Что означают точки?
Получаем доступ к io через java, для того, чтобы получить доступ к IOException? Что означают.
Ошибка при использовании атрибута alt
Доброго времени суток, значит пишу я такой код: <img.
Что означают эти точки в этой?
Что означают эти точки в этой? Страницы 122. Ссылка на книгу.
Что означают точки в приведенной строке
Здравствуйте . подскажите что означают точки в этой строке if (($item eq «.») || ($item eq.
Скрипт, две точки нужны, чтобы подняться на уровень вверх в иерархии папок.
Например, такая команда:
Еще пример. Пусть в папке SomeFolder лежат папки FolderA и FolderB. Вы посмотрели папку FolderA:
Потом вы захотели посмотреть папку FolderB. Находясь в папке FolderA, вы можете вызвать команду Dir следующим образом:
И это будет эквивалентно команде
Aksima, но, на первый взгляд, нет смысла в том, что функция «Dir» возвращает «.» и «..».
Две точки ещё можно, наверное, как-то применить, а одну точку я не представляю, где можно использовать.
Я считаю, что это бред, что функция «Dir» возвращает «.» и «..» и даже в справке ничего не сказано про эти точки.
5-я и 6-я строчка — то, что Вы не увидели самостоятельно.
ikki, и как строки 5 и 6 отвечают на вопрос темы?
Вопрос такой: зачем функция «Dir» возвращает эти точки? Что с ними делать?
Скрипт, тогда и у меня к Вам вопрос — Вы не в состоянии прочитать 8 английских слов в комментарии в 5-й строке кода?
или Вы не знаете английский язык даже на таком уровне?
или Вас забанили во всех сервисах онлайн-переводчиков и словарей?
это такие директории (папки)
текущая и родительская
они есть
в любой директории
и функция их возвращает
как и другие директории (папки)
она их не может не вернуть только из-за того, что они не нравятся лично Вам или из-за того, что Вы до сих пор о них не слышали
эти папки вообще-то пришли даже не из DOS, они есть и в UNIX
есть до сих пор, и они не устаревшие и не бесполезные.
что с ними можно делать — Вам уже рассказали, хотя к теме форума VBA это имеет о-о-очень отдалённое отношение. зачем я буду повторяться?
имхо, вопросы, относящиеся к операционным системам, следует задавать в форуме по операционным системам.
кроме того, я отвечал не на Ваш вопрос (он неинтересный, и тему я даже не читал, пока не начал писать текущее сообщение в ответ на Ваше занудство)
в сообщении #5 я отвечал на то, что я привел в виде цитаты — а именно Ваше лживое утверждение, что в справке «ничего не сказано про эти точки»
сказано.
да, сказано немного, но этого вполне достаточно.
VBA Dir Function to Check if File Exists
The VBA Tutorials Blog
Use the VBA Dir function to check if a file exists. The VBA Dir function returns the name of a valid file, so you can use it to test whether a file exists. When the VBA Dir function returns an empty string, it means the file does not exist.
The Dir function can do a lot more than just tell you whether or not a file exists. It can be used to analyze folders and check file properties, as well. Today, however, I’m going to introduce you to an easy-to-remember user defined function to test if a file exists.
This function I created, named FileExists , is a boolean so it will return True if the file exists and False if the file doesn’t exist. All you have to do is copy and paste the function to a module and pass it a string with the file path you want to check.
VBA Check if File Exists
Make powerful macros with our free VBA Developer Kit
Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit to supplement this tutorial. Grab it below and you’ll be writing macros so much faster than you are right now.
How to use the FileExists UDF
Once you’ve copied and pasted the above macro into a module in your VBA editor, you can begin using the function. The function only accepts 1 argument, so it’s simple to use!
Just pass it a path name or a variable containing a path name to see it work. Here’s an example:
That’s pretty easy to remember, right?
More about the VBA Dir Function
This isn’t the first time you’ve seen me use the Dir function. I’ve used it in the past to count files in a folder and loop through files in a folder. It’s quite versatile!
The VBA Dir function is pretty smart, too. It can accept wildcards, like the asterisk (*) and question mark (?).
- Asterisk (*) — Used to search multiple unknown characters. For example, “a*.txt” will cause Dir to search for a file of any length beginning with an “a” and ending with a “.txt”
- Question Mark (?) — Used to search individual unknown characters. For example, “B?.txt” will cause Dir to search for a file with a 2 letter prefix beginning with a B, like “B1.txt” or “Bc.txt”
If wildcards are used, the Dir function will return the name of the FIRST file it finds meeting the criteria. My FileExists function will return True if any file is found meeting the wildcard conditions.
Here’s a quick demo showing how to use my FileExists Function with a wildcard to see if a file exists.
VBA Dir Second Argument
Believe it or not, the Dir function can do even more! It accepts an optional second argument so you can restrict your search to files meeting certain attribute parameters. I don’t find myself having to use these arguments that often, but here they are if you want to know:
- vbNormal (default)
- vbReadOnly
- vbHidden
- vbSystem
- vbVolume
- vbDirectory
- vbAlias
Mac Users and the Dir Function
I’m going to warn you right now that wildcards only work with the Dir function on a Windows operating system. Since asterisks and question marks are valid file name characters for Mac users, you can not pass wildcards to the VBA Dir function on a Mac.
Instead, Mac users can use the optional second argument to pass the Dir function a MacID defining what file type to search for. For example, to search for text files, you can use something like:
I don’t own a Mac, so I can’t test it but I believe the MacID function must accept a string that’s four characters long. With that said, I don’t know what the MacID of files like PDFs are if you need to search for a PDF with a certain name in a folder. Leave a comment if you know the answer!
The second limitation of MacIDs is they only exist for files created on the Mac. If you’re accessing a server with files created by Macs and PCs, the PC files will not have MacIDs.
I hope you enjoyed this little tutorial. I have more grab-and-go macro examples in my VBA Code Library. Grab what you need!
For more VBA tips, techniques, and tactics, subscribe to our VBA Insiders email series using the form below.
After you subscribe, share what you’re automating on Twitter and Facebook.
Oh, and if you have a question, post it in our VBA Q&A community.
The best free VBA training on the web
I see people struggling with Excel every day and I want to help. That’s why I’m giving away my 90-days to Master VBA eCourse and my entire personal macro library for free.
Over 2 million people use our VBA tutorials each year to help automate their work. Are you ready to reclaim your time, too? Grab our VBA Cheat Sheets and you’ll be writing macros like a professional. With over 180 tips and 135 macro examples, they include everything you need to know to become a great VBA programmer.
VBA DIR Function
Excel VBA DIR Function
VBA DIR function is also known as the directory function, this is an inbuilt function in VBA which is used to give 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 string as it returns the name of the file, there are two arguments to this function which are the pathname and the attributes.
DIR function returns the very first file name in the specified folder path. For example, in your D Drive if you have folder name called 2019 and in that folder, if you excel file named as “2019 Sales” then you can access this file by using DIR function.
“VBA DIR” function is very helpful in getting the name of the file by using its path folder.
Syntax
This function has two optional arguments.
- [Path Name]: As the name say what the path to access the file is. This could be the name of the file, name of the folder, or directory as well. If any path is not assigned I will return empty string value i.e. “”
- [Attributes]: This is also an optional argument and you may not use this very often in coding. You can specify the attribute of the file in the [Path Name] and 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.
Examples to use VBA DIR Function
Example #1 – Accessing the File Name using DIR Function
I will explain to you 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:
Step 3: Now for this variable, we will assign value by using DIR function.
Code:
Step 4: Now copy and paste the file folder path in your computer. Mention the pathname in double-quotes.
Code:
Step 5: I have mentioned my path to the folder, now we need to mention the file name & its extension as well. To do this first thing we need to do is we need to put a backslash after the path ()
After entering the backslash we need to enter the full file name.
Code:
Step 6: Show the value of the variable in the message box.
Функции, используемые в процедурах VBA
Настоящая заметка продолжает знакомство с VBA. В ней представлены некоторые «практичные» функции, которые могут использоваться в ваших приложениях либо помогут в создании аналогичных функций. Эти функции наиболее полезны, когда вызываются из другой процедуры VBA. Следовательно, они объявляются с ключевым словом Private и не отображаются в диалоговом окне Excel Мастер функций (подробнее см. Работа с процедурами VBA).[1]
Функция FileExists
Данная функция получает один аргумент (путь и имя файла) и возвращает ИСТИНА, если файл существует.
Скачать заметку в формате Word или pdf, примеры в архиве (политика безопасности провайдера не позволяет загружать файлы Excel с поддержкой макросов)
Функция FileNameOnly
Функция получает один аргумент (путь и имя файла; не забывайте брать строку в кавычки) и возвращает только имя файла.
Функция использует функцию VBA Split, которая принимает строку (вместе с символами-разделителями) и возвращает массив типа variant, содержащий элементы, которые находятся между символами-разделителями. В рассматриваемом случае переменной temp присваивается массив, содержащий текстовые строки между Application.PathSeparater (обычно в качестве разделителя используется обратная косая черта).
Если в качестве аргумента указать » с:excelfiles2010backupbudget.xlsx » , функция возвратит строку budget.xlsx.
Функция FileNameOnly обрабатывает любой путь и имя файла (даже если файла не существует). Если файл существует, лучше воспользоваться следующей более простой функцией.
Функция PathExists
Функция получает один аргумент (путь) и возвращает ИСТИНА, если путь существует.
Функция RangeNameExists
Функция получает один аргумент (название диапазона) и возвращает ИСТИНА, если в активной рабочей книге существует указанное название диапазона.
Функция SheetExists
Функция получает один аргумент (название рабочего листа) и возвращает ИСТИНА, если данный рабочий лист существует в активной рабочей книге.
Функция WorkbooklsOpen
Функция получает один аргумент (название рабочей книги) и возвращает ИСТИНА, если данная рабочая книга открыта.
Проверка принадлежности к коллекции
Следующая функция представляет собой образец «групповой» функции, с помощью которой можно определить, является ли объект членом коллекции.
Эта функция имеет два аргумента: коллекцию (объект) и элемент (строка), который может быть либо не быть членом коллекции. Функция будет создавать объектную переменную, представляющую элемент коллекции. Если попытка увенчается успехом, функция возвратит True; иначе — False. Функцию IsInCollection можно использовать вместо трех других функций, приведенных выше. Чтобы определить, содержится ли в активной рабочей книге диапазон Data, вызовите функцию IsInCollection с помощью следующего оператора:
MsgBox IsInCollection(ActiveWorkbook.Names, » Data » )
Для того чтобы определить, открыта ли рабочая книга с названием Budget, используйте следующий оператор:
MsgBox IsInCollection(Workbooks, » budget.xlsx » )
Чтобы узнать, содержит ли активная рабочая книга рабочий лист Лист1, используйте следующий оператор:
MsgBox IsInCollection(ActiveWorkbook.Worksheets, » Лист1 » )
Получение значения из закрытой рабочей книги
В VBA не существует метода получения значения из закрытого файла рабочей книги. Однако вы можете воспользоваться возможностью управления ссылками на файлы, которая предоставляется в Excel. В настоящем разделе описана функция VBA GetValue, которая получает значение из закрытой книги. Эта задача выполняется в результате вызова макроса XLM, который появился в «доисторических» версиях Excel (до версии 5), но поддерживается до сих пор (подробнее о макрофункциях xlm см. Функция Получить.Ячейку).