Vba узнать что файл excel

Открыта или закрыта книга Excel? Проверяем с помощью кода VBA по краткому или полному имени файла, используя объектную переменную, цикл или оператор Open.

Проверка по краткому имени

Способ проверки по краткому имени, открыта ли рабочая книга, позволяет определить состояние проверяемой книги в том же экземпляре приложения Excel, в котором открыта книга с проверяющим кодом.

Использование объектной переменной

Вариант пользовательской функция VBA Excel, предназначенной для проверки, открыта или закрыта рабочая книга, путем определения результата присвоения ссылки на нее объектной переменной. Присвоение состоялось (BookOpenClosed = True) – книга открыта, произошла ошибка и присвоение не состоялось (BookOpenClosed = False) – книга закрыта.

Function BookOpenClosed(wbName As String) As Boolean

    Dim myBook As Workbook

    On Error Resume Next

        Set myBook = Workbooks(wbName)

    BookOpenClosed = Not myBook Is Nothing

End Function

Аргумент функции:

  • wbName – краткое имя проверяемой рабочей книги.

Перебор открытых книг циклом

Этот вариант функции BookOpenClosed перебирает с помощью цикла все открытые книги Excel и проверяет их краткие имена на совпадение с кратким именем проверяемой книги. Совпадение найдено (BookOpenClosed = True) – книга открыта, совпадение не найдено (BookOpenClosed = False) – книга закрыта.

Function BookOpenClosed(wbName As String) As Boolean

    Dim myBook As Workbook

    For Each myBook In Workbooks

        If myBook.Name = wbName Then

            BookOpenClosed = True

            Exit For

        End If

    Next

End Function

В коллекцию Workbooks входят и скрытые книги, в том числе Личная книга макросов, и книга с функцией.

Проверка по полному имени

Проверка по полному имени с помощью оператора Open позволяет узнать, открыта ли рабочая книга каким-либо другим процессом: текущим экземпляром Excel, в котором открыта книга с проверяющим кодом, другим экземпляром Excel или сторонним приложением.

Function BookOpenClosed(wbFullName As String) As Boolean

    Dim ff As Integer

    ff = FreeFile

        On Error Resume Next

        Open wbFullName For Random Access Read Write Lock Read Write As #ff

        Close #ff

    BookOpenClosed = (Err.Number <> 0)

End Function

Аргумент функции:

  • wbFullName – полное имя проверяемой рабочей книги.

Эта функция открывает с помощью оператора Open файл проверяемой книги с разрешением чтения и записи (параметр access) и запретом чтения и записи, если этот файл уже открыт другим процессом (параметр lock).

Если файл уже открыт другим процессом, а указанный тип доступа (параметр access) не разрешен (параметр lock), операция открытия завершится с ошибкой, а выражение (Err.Number <> 0) возвратит значение True.

Примеры проверки состояния книги

По краткому имени

Sub Primer1()

    If BookOpenClosed(«Книга1.xlsx») Then

        MsgBox «Книга открыта»

    Else

        MsgBox «Книга закрыта»

    End If

End Sub

По полному имени

Sub Primer2()

    If BookOpenClosed(«C:Папка1Папка2Папка3Книга1.xlsx») Then

        MsgBox «Книга открыта»

    Else

        MsgBox «Книга закрыта»

    End If

End Sub


Содержание

  1. Проверка файла VBA существует — Функция VBA DIR для проверки наличия файла
  2. Проверьте наличие файла с помощью Excel VBA
  3. Как использовать файл проверки VBA в Excel?
  4. Пример № 1 — файл проверки VBA существует
  5. Пример № 2 — DIR с условием IF
  6. Рекомендуемые статьи
  7. VBA Excel. Открыта или закрыта книга (проверка состояния)
  8. Проверка по краткому имени
  9. Использование объектной переменной
  10. Перебор открытых книг циклом
  11. Проверка по полному имени
  12. Примеры проверки состояния книги
  13. По краткому имени
  14. По полному имени
  15. 6 комментариев для “VBA Excel. Открыта или закрыта книга (проверка состояния)”
  16. VBA Dir Function to Check if File Exists
  17. The VBA Tutorials Blog
  18. VBA Check if File Exists
  19. How to use the FileExists UDF
  20. More about the VBA Dir Function
  21. VBA Dir Second Argument
  22. Mac Users and the Dir Function
  23. VBA Check if File or Folder Exists
  24. Using the Dir Command to Check If a File Exists
  25. Using the Dir Command to Check If a Folder Exists
  26. VBA Coding Made Easy
  27. VBA Code Examples Add-in

Проверка файла VBA существует — Функция VBA DIR для проверки наличия файла

Проверьте наличие файла с помощью Excel VBA

VBA Check File Exists помогает проверить, существует ли файл в Location с помощью Excel VBA. После упоминания пути к файлу на компьютере, что если кто-то удалит файл или изменит путь к папке с файлом, очевидно, что в этом случае наш код выдаст ошибку. Чтобы решить эту проблему, мы можем сделать одну вещь, прежде чем мы действительно откроем файл, мы можем проверить, существует ли упомянутый файл или нет.

В этой статье мы покажем вам, как проверить, существует ли указанный файл или нет.

Как проверить, существует файл или нет?

  • Как Excel VBA знает, существует ли файл или нет ??
  • По умолчанию это не может .
  • Так как же тогда ??
  • Нам нужно использовать функцию под названием «Dir», чтобы проверить, существует файл или нет.

Что делает функция DIR?

Функция VBA DIR возвращает имя имени файла с его расширением в указанном пути к папке. Если в папке нет файла, она возвращает пустую строку.

Таким образом, используя эту функцию, мы можем на самом деле проверить, существует файл или нет. Даже без функции DIR мы можем проверить, существует файл или нет. Мы увидим некоторые примеры ниже.

Как использовать файл проверки VBA в Excel?

Мы узнаем, как использовать функцию проверки наличия файлов VBA, с несколькими примерами в Excel.

Вы можете скачать этот файл Excel с шаблоном проверки VBA здесь — Шаблон проверки VBA с файлом Excel существует

Пример № 1 — файл проверки VBA существует

Хорошо, давайте напишем некоторый код, чтобы проверить, существует файл или нет. Выполните следующие шаги, чтобы написать код самостоятельно.

Шаг 1: Для этого перейдите в окно VBA и в меню «Вставка» выберите «Модуль», как показано ниже.

Шаг 2: Запустите подпроцедуру.

Код:

Шаг 3: Определите переменную как String.

Код:

Шаг 4: Теперь я хочу протестировать файл с именем «Глава-11. InputBoxes.xlsm ”в моем E-Drive”. Я назначу свой путь к файлу этой переменной.

Код:

Шаг 5: Теперь определите еще одну переменную для применения функции DIR.

Код:

Шаг 6: Теперь для второй переменной откройте функцию DIR.

Код:

Шаг 7: Функция DIR требует путь к файлу. Поскольку мы уже присвоили путь к файлу переменной «FilePath», мы можем просто передать эту переменную в функцию DIR.

Код:

Шаг 8: Теперь функция DIR возвращает только имя файла как «Глава-11. InputBoxes »из указанного пути к файлу. Итак, давайте покажем результат в окне сообщения.

Код:

Шаг 9: Теперь запустите макрос, чтобы увидеть результат.

Поскольку в указанном пути существует файл, наша функция DIR отфильтровывает имя файла по огромному пути.

Шаг 10: Теперь я изменю имя файла на другое, чего нет в указанном пути.

Код:

Шаг 11: Если я сейчас запусту код, он вернет пустую строку в окне сообщения.

Функция DIR лучше всего подходит для использования с оператором IF в VBA. Выше мы могли видеть только имя файла с его расширением, если оно существует, иначе мы могли видеть только пустую строку.

Пример № 2 — DIR с условием IF

Шаг 1: Но используя оператор IF с функцией DIR, мы можем изменить наши результаты. Для примера посмотрите на код ниже.

Код:

Шаг 2: Здесь условие IF проверяет, является ли значение переменной «FileExists» ничем («») или нет. Если значение переменной — ничто («»), то он вернет результат как «Файл не существует в указанном пути», либо он вернет результат как «Файл существует в указанном пути»

Ниже приведен пример того же скриншота.

Используя функцию DIR, мы можем проверить, существует файл или нет.

Рекомендуемые статьи

Это руководство к VBA Check File Exists. Здесь мы обсудим, как использовать функцию проверки наличия файла в Excel VBA, а также с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Функция копирования и вставки в VBA
  2. Функция подстроки Excel
  3. Индекс VBA вне диапазона
  4. Excel ISNUMBER Formula

Источник

VBA Excel. Открыта или закрыта книга (проверка состояния)

Открыта или закрыта книга Excel? Проверяем с помощью кода VBA по краткому или полному имени файла, используя объектную переменную, цикл или оператор Open.

Проверка по краткому имени

Способ проверки по краткому имени, открыта ли рабочая книга, позволяет определить состояние проверяемой книги в том же экземпляре приложения Excel, в котором открыта книга с проверяющим кодом.

Использование объектной переменной

Вариант пользовательской функция VBA Excel, предназначенной для проверки, открыта или закрыта рабочая книга, путем определения результата присвоения ссылки на нее объектной переменной. Присвоение состоялось (BookOpenClosed = True) – книга открыта, произошла ошибка и присвоение не состоялось (BookOpenClosed = False) – книга закрыта.

  • wbName – краткое имя проверяемой рабочей книги.

Перебор открытых книг циклом

Этот вариант функции BookOpenClosed перебирает с помощью цикла все открытые книги Excel и проверяет их краткие имена на совпадение с кратким именем проверяемой книги. Совпадение найдено (BookOpenClosed = True) – книга открыта, совпадение не найдено (BookOpenClosed = False) – книга закрыта.

В коллекцию Workbooks входят и скрытые книги, в том числе Личная книга макросов, и книга с функцией.

Проверка по полному имени

Проверка по полному имени с помощью оператора Open позволяет узнать, открыта ли рабочая книга каким-либо другим процессом: текущим экземпляром Excel, в котором открыта книга с проверяющим кодом, другим экземпляром Excel или сторонним приложением.

  • wbFullName – полное имя проверяемой рабочей книги.

Эта функция открывает с помощью оператора Open файл проверяемой книги с разрешением чтения и записи (параметр access) и запретом чтения и записи, если этот файл уже открыт другим процессом (параметр lock).

Если файл уже открыт другим процессом, а указанный тип доступа (параметр access) не разрешен (параметр lock), операция открытия завершится с ошибкой, а выражение (Err.Number <> 0) возвратит значение True.

Примеры проверки состояния книги

По краткому имени

По полному имени

6 комментариев для “VBA Excel. Открыта или закрыта книга (проверка состояния)”

Большое спасибо за подробную информацию

Примеры проверки состояния книги
По краткому имени
Сначала вставляем функцию, потом код в макрос.
все работает

Добрый день!
При вставке данной функции появляется ошибка «Sub or function not defined». Что это значит и как ее исправить?

Здравствуйте, Анна!
Такая ошибка может произойти, когда имя функции в вызывающей ее процедуре записано с ошибкой. Также, обратите внимание, что функция BookOpenClosed должна быть с таким именем одна в модуле.

Источник

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

It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.

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 name 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.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

VBA Check if File or Folder Exists

VBA allows you to check if a file or folder exists by using the Dir function.

Using the Dir Command to Check If a File Exists

As we mentioned in the introduction, the Dir function allows us to check if a selected file exists on the computer. Here is the code:

We first assigned the file path to the variable strFileName. Then we use the Dir function to get the file name into the variable strFileExists. If the file exists in the directory, its name will be assigned to the string variable strFileExists. If it does not exist then strFileExists will remain blank. Finally, the message box appears informing us if the file exists or not.

Using the Dir Command to Check If a Folder Exists

Similarly to checking if a file exists, you can check if a folder exists. You just need to add one argument to the Dir command. Let’s look at the code:

We first assigned the folder path to the variable strFolderName. Then we use the Dir function to get the file name into the variable strFileExists. In order to check a folder, we need to add the second argument to the function – vbDirecotry. If the folder exists in the directory, its name will be assigned to the variable strFolderExists. If not strFolderExists will remain blank.

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 Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

0 / 1 / 3

Регистрация: 18.10.2012

Сообщений: 662

1

09.06.2017, 14:54. Показов 7385. Ответов 8


Студворк — интернет-сервис помощи студентам

Ребята здравствуйте! много чего просмотрел в инете так и ни чего конкретного для себя не нашел, подскажите Как узнать открыт(именно открыт ли конкретный файл) ли файл XL или нет, если ДА то msgbox если нет то продолжить



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

09.06.2017, 14:54

8

Alex77755

11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

09.06.2017, 15:06

2

А имеет ли значение тип файла?
Попробуй такой вариант:

Visual Basic
1
2
3
4
5
6
7
8
Function IsBookOpen(wbFullName As String) As Boolean
    Dim iFF As Integer
    iFF = FreeFile
    On Error Resume Next
    Open wbFullName For Random Access Read Write Lock Read Write As #iFF
    Close #iFF
    IsBookOpen = Err
End Function



1



ASSEI

0 / 1 / 3

Регистрация: 18.10.2012

Сообщений: 662

09.06.2017, 15:42

 [ТС]

3

запускаю его так

Visual Basic
1
2
3
Set XL = CreateObject("Excel.Application")
XL.WorkBooks.Open App.Path & "BDПКО_РКО.xlsx"
XL.Visible = False

получается что у меня файл скрытный

Добавлено через 18 минут
не получается с вашим кодом



0



11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

09.06.2017, 16:54

4

не вижу проверки на открытость

Добавлено через 5 минут
прежде чем открывать надо проверить!



1



ASSEI

0 / 1 / 3

Регистрация: 18.10.2012

Сообщений: 662

09.06.2017, 17:08

 [ТС]

5

у меня почему то ни чего не получается устанавливаю ваш код в загрузку формы перед свои кодом ругается на строку формы

Visual Basic
1
Private Sub Form_Load()

Добавлено через 6 минут
у меня почему то ни чего не получается устанавливаю ваш код в загрузку формы перед свои кодом ругается на строку формы

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Private Sub Form_Load()
 
Function IsBookOpen(wbFullName As String) As Boolean
    Dim iFF As Integer
    iFF = FreeFile
    On Error Resume Next
    Open wbFullName For Random Access Read Write Lock Read Write As #iFF
    Close #iFF
    IsBookOpen = Err
End Function
 
Set XL = CreateObject("Excel.Application")
XL.WorkBooks.Open App.Path & "BDПКО_РКО.xlsx"
XL.Visible = False
End Sub



0



11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

09.06.2017, 17:09

6

хммм
я предлагал функцию!
её надо вызвать! и в зависимости от того, что она вернёт принимать решение… как-то так



2



ASSEI

0 / 1 / 3

Регистрация: 18.10.2012

Сообщений: 662

09.06.2017, 17:52

 [ТС]

7

мне пока сложно это все можно в коде показать?

Добавлено через 18 минут
вот что у меня получилось и вроде все сработало!

Visual Basic
1
2
3
4
5
6
7
8
Dim XL As Object
On Error Resume Next
   Set XL = CreateObject("Excel.Application")
  If Err.Number <> 0 Then
   MsgBox "файл открыт"
Else
   MsgBox "файл закрыт"
End If

Добавлено через 14 минут
ПРАВДА ГОВОРЯ РЕАГИРУЕТ НА ЛЮБОЙ ФАЙЛ XL А ХОТЕЛОСЬ БЫ НА ОПРЕДЕЛЕННЫЙ КОТОРЫЙ НАХОДИТСЯ В ПАПКЕ



0



Alex77755

11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

10.06.2017, 15:49

8

Не надо функцию впихивать в процедуру!
Её надо вызвать и в зависимости от того, что она вернёт действовать
Как-то так. не проверял

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Private Sub Form_Load()
 
msgbox IsBookOpen(App.Path & "BDПКО_РКО.xlsx")
 
Set XL = CreateObject("Excel.Application")
XL.WorkBooks.Open App.Path & "BDПКО_РКО.xlsx"
XL.Visible = False
End Sub
 
 
Function IsBookOpen(wbFullName As String) As Boolean
    Dim iFF As Integer
    iFF = FreeFile
    On Error Resume Next
    Open wbFullName For Random Access Read Write Lock Read Write As #iFF
    Close #iFF
    IsBookOpen = Err
End Function



1



ASSEI

0 / 1 / 3

Регистрация: 18.10.2012

Сообщений: 662

12.06.2017, 10:11

 [ТС]

9

вот так у меня все заработало! спасибо вам !

Visual Basic
1
2
3
4
5
If IsBookOpen(App.Path & "BDПКО_РКО.xlsx") = False Then
MsgBox "файл Закрыт"
Else
   MsgBox "файл Открыт"
End If



0



I use extensive Excel-Word linking, updated manually with VBA code. If the Excel file is not open, Word attempts to open it, warns that opening it again is trouble, requires a dialog box be answered, then go to the next link and starts again. Since there are usually 100 links, this is a big problem.

I found simple VBA code that calls a function to check if Excel is running.

    Dim sApp As String
    sApp = "Excel.Application"
    If IsAppRunning(sApp) = True Then
        MsgBox "Excel is Running, continue" & SourceFileName
    Else
        MsgBox "Excel is NOT Running, abort"
        Exit Sub
    End If

I want to check if the RIGHT Excel file is open. The «right» file will have the same name as the Word file, e.g., MyDocSample.doc will be linked to MyDocSample.xls.

If MyDocSample.xls is open, then continue, if not, a warning should be posted saying «MyDocSample.xls» is not open, and offer an Abort selection.

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir("thesentence") <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

In this when i pickup the text value from the input box, it doesn’t work. If however, if remove "the sentence" from If Dir() and replace it with an actual name in the code, it works. Can somebody help?

vba_user111's user avatar

asked Jul 20, 2012 at 6:25

Dinesh Goel's user avatar

Note your code contains Dir("thesentence") which should be Dir(thesentence).

Change your code to this

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

answered Jul 20, 2012 at 6:31

Cylian's user avatar

CylianCylian

10.8k4 gold badges43 silver badges55 bronze badges

4

Use the Office FileDialog object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library and look in the help. This is much better than having people enter full paths.

Here is an example using msoFileDialogFilePicker to allow the user to choose multiple files. You could also use msoFileDialogOpen.

'Note: this is Excel VBA code
Public Sub LogReader()
    Dim Pos As Long
    Dim Dialog As Office.FileDialog
    Set Dialog = Application.FileDialog(msoFileDialogFilePicker)

    With Dialog
        .AllowMultiSelect = True
        .ButtonName = "C&onvert"
        .Filters.Clear
        .Filters.Add "Log Files", "*.log", 1
        .Title = "Convert Logs to Excel Files"
        .InitialFileName = "C:InitialPath"
        .InitialView = msoFileDialogViewList

        If .Show Then
            For Pos = 1 To .SelectedItems.Count
                LogRead .SelectedItems.Item(Pos) ' process each file
            Next
        End If
    End With
End Sub

There are lots of options, so you’ll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you’ll need to find the correct help for the version you’re using).

answered Jul 20, 2012 at 7:19

ErikE's user avatar

ErikEErikE

48.4k23 gold badges150 silver badges194 bronze badges

1

Correction to fileExists from @UberNubIsTrue :

Function fileExists(s_directory As String, s_fileName As String) As Boolean

  Dim obj_fso As Object, obj_dir As Object, obj_file As Object
  Dim ret As Boolean
   Set obj_fso = CreateObject("Scripting.FileSystemObject")
   Set obj_dir = obj_fso.GetFolder(s_directory)
   ret = False
   For Each obj_file In obj_dir.Files
     If obj_fso.fileExists(s_directory & "" & s_fileName) = True Then
        ret = True
        Exit For
      End If
   Next

   Set obj_fso = Nothing
   Set obj_dir = Nothing
   fileExists = ret

 End Function

EDIT: shortened version

' Check if a file exists
Function fileExists(s_directory As String, s_fileName As String) As Boolean

    Dim obj_fso As Object

    Set obj_fso = CreateObject("Scripting.FileSystemObject")
    fileExists = obj_fso.fileExists(s_directory & "" & s_fileName)

End Function

answered May 29, 2013 at 19:14

amackay11's user avatar

amackay11amackay11

7191 gold badge10 silver badges17 bronze badges

3

just get rid of those speech marks

Sub test()

Dim thesentence As String

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

This is the one I like:

Option Explicit

Enum IsFileOpenStatus
    ExistsAndClosedOrReadOnly = 0
    ExistsAndOpenSoBlocked = 1
    NotExists = 2
End Enum


Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus

With New FileSystemObject
    If Not .FileExists(FileName) Then
        IsFileReadOnlyOpen = 2  '  NotExists = 2
        Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
    End If
End With

Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
    iFilenum = FreeFile()
    Open FileName For Input Lock Read As #iFilenum
    Close iFilenum
    iErr = Err
On Error GoTo 0

Select Case iErr
    Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
    Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
    Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select

End Function    'IsFileReadOnlyOpen

answered Jul 21, 2012 at 13:52

whytheq's user avatar

whytheqwhytheq

34k64 gold badges170 silver badges265 bronze badges

4

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

Works very well, almost, at my site. If I call it with «» the empty string, Dir returns «connection.odc«!! Would be great if you guys could share your result.

Anyway, I do like this:

Function FileExists(fullFileName As String) As Boolean
  If fullFileName = "" Then
    FileExists = False
  Else
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
  End If
End Function

answered Oct 22, 2015 at 11:12

Joachim Brolin's user avatar

1

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

answered Jun 14, 2015 at 2:09

Ronnie Royston's user avatar

Ronnie RoystonRonnie Royston

16k6 gold badges73 silver badges88 bronze badges

0

I’m not certain what’s wrong with your code specifically, but I use this function I found online (URL in the comments) for checking if a file exists:

Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean
    'Code from internet: http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
    'Returns True if the passed sPathName exist
    'Otherwise returns False
    On Error Resume Next
    If sPathName <> "" Then

        If IsMissing(Directory) Or Directory = False Then

            File_Exists = (Dir$(sPathName) <> "")
        Else

            File_Exists = (Dir$(sPathName, vbDirectory) <> "")
        End If

    End If
End Function

answered Jul 20, 2012 at 6:31

Dan's user avatar

DanDan

44.9k17 gold badges88 silver badges157 bronze badges

2

Very old post, but since it helped me after I made some modifications, I thought I’d share. If you’re checking to see if a directory exists, you’ll want to add the vbDirectory argument to the Dir function, otherwise you’ll return 0 each time. (Edit: this was in response to Roy’s answer, but I accidentally made it a regular answer.)

Private Function FileExists(fullFileName As String) As Boolean
    FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function

answered Dec 19, 2018 at 3:55

Word Nerd's user avatar

based on other answers here I’d like to share my one-liners that should work for dirs and files:

  • Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0  'version 1 - ... <> "" should be more inefficient generally
    
    • (just Len(Dir(path)) did not work for directories (Excel 2010 / Win7))
  • CreateObject("Scripting.FileSystemObject").FileExists(path)  'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
    

as PathExists(path) function:

Public Function PathExists(path As String) As Boolean
    PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function

answered Aug 12, 2019 at 9:21

Andreas Covidiot's user avatar

Andreas CovidiotAndreas Covidiot

4,1785 gold badges50 silver badges95 bronze badges

Понравилась статья? Поделить с друзьями:
  • Vba удаление таблицы word
  • Vba убрать все пробелы в ячейке excel
  • Vba только для чтения word на
  • Vba таблицы excel примеры
  • Vba строка состояния excel