Exists vba excel - Мир ПК
Fruitsekta.ru

Мир ПК
168 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Exists vba excel

Exists vba excel

Если вы программируете на VBA/VBS, то рано или поздно вынуждены будете познакомиться с объектом Dictionary . Если в двух словах, то Dictionary — это продвинутый массив. Как вы знаете, массив — это упорядоченный набор неких (обычно однородных) элементов. Вот типичный массив:

Элементы пронумерованы и доступны по номеру индекса. Индекс всегда числовой.

А вот, что из себя представляет Dictionary (словарь):

Как видите, каждому элементу поставлен в соответствие не просто числовой индекс, а уникальный ключ, который в данном случае представляет из себя текстовую строку (имена). Двух одинаковых ключей в словаре быть не может, но могут быть одинаковые элементы (хоть все одинаковые). Таким образом словарь — это обычно некий список, снабжённый ключом, при помощи которого вы хотите извлекать полезную информацию (элементы). В указанном примере мы имеем, допустим, имена детей в качестве ключа, а в качестве элементов, поставленных в соответствие ключу, скажем, количество карманных денег у ребёнка.

С другой стороны нечто подобное можно же сделать, используя массив. Давайте объявим двумерный массив:

Должно быть у словаря есть какие-то преимущества перед таким использованием массивов? И это действительно так!

Давайте пока просто перечислим важнейшие преимущества:

Словарь контролирует уникальность ключей. Два одинаковых ключа не могут быть добавлены в словарь. Это важное свойство, так как программисту очень часто требуется обеспечить или проконтролировать уникальность каких-либо наборов значений, и в этом может с успехом быть использован Dictionary ;

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

У словаря есть встроенный метод ( Exists ), при помощи которого можно понять, добавлен ли некий ключ в коллекцию;

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

Словарь может вернуть все ключи и все элементы в виде отдельных одномерных массивов.

2. Создание Dictionary

Существует несколько способов создать объект типа Dictionary . Ознакомимся с ними:

Считается, что методы, использующие позднее связывание надёжнее в плане обеспечения работоспособности программы на разных компьютерах, так как не зависят от настроек Tools — References. редактора VBA.

Однако, учитывая, что библиотека Microsoft Scripting Runtime присутствует везде, начиная с Windows 2000 , я думаю, что вы без какого-либо ущерба можете использовать методы раннего связывания. Раннее связывание хорошо тем, что оно несколько быстрее работает, а также во время разработки вы можете пользоваться функцией завершения кода (когда среда программирования вам подсказывает имеющиеся у объекта свойства и методы). Выбор за вами.

3. Свойства и методы объекта Dictionary

ТипИдентификаторОписание
СвойствоCountdicObject.Count
Возвращает количество элементов в словаре. Только для чтения.
СвойствоItemdicObject.Item(key)[ = newitem]
Устанавливает или возвращает элемент с указанным ключом. Чтение/запись.
СвойствоKeydicObject.Key(key) = newkey
Заменяет ключ элемента на новое значение.
СвойствоCompareModedicObject.CompareMode[ = compare]
Устанавливает и возвращает режим сравнения текстовых ключей в словаре. Чтение/запись.
МетодAdddicObject.Add (key, item)
Добавляет пару ключ-элемент в словарь.
МетодExistsdicObject.Exists(key)
Возвращает true, если указанный ключ существует в словаре, либо false — в противном случае.
МетодItemsdicObject.Items( )
Возвращает массив, состоящий из всех элементов, имеющихся в коллекции.
МетодKeysdicObject.Keys( )
Возвращает массив, состоящий из всех ключей, имеющихся в коллекции.
МетодRemovedicObject.Remove(key)
Удаляет из словаря элемент с указанным ключом.
МетодRemoveAlldicObject.RemoveAll( )
Полностью очищает словарь от элементов. Сам объект словаря при этом не уничтожается.

4. Наполнение словаря

4.1. Типы данных ключа и элемента

Dictionary наполняется по одному элементу. Не существует способов наполнить словарь массово. Чтобы добавить в словарь новый элемент вы должны иметь уникальный ключ и сам элемент, который под этим ключом будет храниться в словаре.

В качестве типа данных для элемента может быть использовано практически всё что угодно: числа, логический тип, строки (в том числе пустые), дата-время, массивы, любые объекты (листы, диапазоны, коллекции, другие словари, пустой указатель Nothing ).

В качестве типа данных для ключа могут быть использованы: числа, строки, дата-время, объекты, но не массивы.

UDT (User Defined Type) не может напрямую использоваться в качестве ключа и/или элемента, но данное ограничение можно обойти, объявив аналог UDT , создав класс и определив в нём свойства аналогичные имеющимся в UDT . А поскольку класс — это объектный тип, то его уже можно использовать для ключей и элементов.

4.2. Через метод Add

На листе Example , прилагаемого к статье файла, есть таблица с TOP30 стран по площади их территории. Для области данных этой таблицы объявлен именованный диапазон SquareByCountry . Пример ниже добавляет все строки указанногот ИД в Dictionary по принципу страна ( key ) — площадь ( item ):

Как видите, для добавления элемента (item) мы в 12-й строке кода использовали метод Add объекта dicCountry . Если в нашей таблице будет задвоена страна, то при попытке добавить в словарь элемента с ключом, который в словаре уже есть, будет сгенерировано исключение:

4.3. Через свойство Item

Используя свойство Item , также можно добавлять пары ключ-элемент, однако, при попытке добавить дублирующий ключ исключения сгенерировано НЕ БУДЕТ , а элемент будет заменён на новый (с потерей старого). Это очень полезно — иметь возможность выбирать способы наполнения словаря, отличающиеся реакцией на задвоение ключей.

4.4. Неявное добавление ключа в Dictionary

И ещё один неожиданный и я бы сказал экзотический способ пополнения словаря. Если упомянуть свойство Item по ПРАВУЮ сторону оператора присваивания, то он оказывается добавит в словарь key с пустым item, если данного key не существует в коллекции. Если же такой key уже существует, то никаких действий предпринято не будет.

Ещё раз хочу обратить ваше внимание, что элемент (item) при таком пополнении коллекции будет пустым ( Empty ). Это можно использовать, если вам нет необходимости что-то хранить в элементах в качестве полезной нагрузки (например, когда вы просто строите список уникальных значений, встречающихся в столбце таблицы).

Читать еще:  Как изменить масштаб диаграммы в excel

Если вы читаете словарь через Item (а это, собственно, самый логичный и распространенный метод), и при этом хотите избежать добавления пустых ключей в словарь, используйте предварительно метод Exists , что контроля наличия такого ключа в коллекции.

5. Удаление элементов

Есть 2 варианта удаления элементов из словаря:

Excel VBA:

Open File or Create Folder

The DIR VBA function plays an important role if you need to refer to other files or folders in your macro.

DIR returns a string that represents a directory or file that matches a defined pattern.

For example, with the DIR function you can check if a specific Excel file exists and then open it in the background, and copy and paste data into the active workbook.

You can also check if a folder exists, if it doesn’t, create a new folder in the directory.

The function that allows us to check if a file or folder exists is know as the DIR function. The syntax for the DIR function is as follows:

The PATH argument is basically an address which returns the name of your file or folder. If the name is not found, DIR returns an empty string.

The ATTRIBUTES argument (which are optional) are listed in the below table.

ConstantvALUEValueDescription
vbNormal(Default) Files with no attributes
vbReadOnly1Read-only files
vbHidden2Hidden files
vbSystem4System files
vbDirectory16Directories or folders

The default is vbNormal, which are files with no specific attributes. You can filter for files with a specific attribute by using the constants listed above.

An interesting thing you can use with the DIR function are wildcards. Wildcards represent “any characters” and are useful when you want to capture multiple items in a search based on a pattern of characters. There are two wildcard characters:

Asterisk (*) – This wildcard character will allow for any character(s) in any quantity.

Example: Exc* (any text starting with “Exc”)

*el (any text ending with “el”)

Exc*el (any text starting with “Exc”, ending with “el”, and any character in between)

Question Mark (?) – This wildcards character will allow for any character in a single character position

Example: ??cel (The first and second characters can be anything, but the third through fifth characters must be “cel”)

Ex?el (The first and second characters must be “Ex”, the fourth and fifth characters must be “el”, but the third character can be anything)

Practical Examples

Task #1

We will use the DIR function to check if a file exists. If the file doesn’t exist, we will display a “File does not exist” message to the user. If the file exists, we will open the file.

In Task #2

We will use the DIR function to check if a folder exists. If the folder doesn’t exist, we will prompt the user to ask if they would like to create that folder. If the responds with a “Yes”, we will create the folder for them.

Task #1 (Version 1) – Checking for the existence of a file

First, open the Visual Basic Editor (ALT-F11) and create an empty module (i.e. “LessonsFilesFolders”).

The DIR function returns a string, so we need to declare a variable named FileName to hold the returned value.

The next step is to query a folder for a file and return the filename if it exists, or an empty string if the file does not exist. We will store the response in the FileName variable we created in the previous step.

FileName = VBA.FileSystem.Dir(“your folder nameyour file name”)

In our example we will use the following code:

If the file does not exist, the DIR function will return an empty string. We will test for the empty string response with an IF statement. If the file does not exist, we will display a message stating such. If the file does exist, this first version will simply show the filename in a message box.

The completed code should look like the following:

Execute the code by pressing F5 and observe the response.

This confirms that the file exists in the defined folder.

Task #1 (Version 2) – Checking for the existence of a file using wildcards

Alter the code to use wildcards when searching for the filename.

We will also alter the code; instead of displaying a message, we will open the requested file.

The updated code should appear as follows:

Execute the code by pressing F5 and observe that the file opens.

Task #2 – Check if a folder exists

In this task, we will check to see if a folder exists. If the folder does not exist, we will prompt the user and ask if they would like to create the folder.

We will create two variables:

Path – Hold the full folderfilename information

Folder – Hold only the folder name

We will set the Path variable to point to a folder that does not exist:

We will set the Folder variable to hold the folder location stored by the Path variable. Because this is a folder, we will use the optional constant vbDirectory in the DIR function.

As we did earlier, we will check to see if the response returns an empty string. If the Folder variable contains an empty string, we will prompt the user to ask if they wish to create the folder.

We need to store the user’s response, so we will create a variable to hold the response.

If the folder does not exist, we will display a message and store the user’s response in the Answer variable.

Now we will test the answer. We will use a Case statement to test the response.

If the user responds with “Yes”, we will create the folder. If the user responds with anything else, we will exit the subroutine.

If the folder does exist, we will inform the user of its existence with a message box response.

The completed code should look like the following:

Execute the code by pressing F5. Because the folder does not exist, we are presented with the following message prompt.

If we answer “Yes”, the folder is created.

If we execute the macro a second time, we see the following response.

This is because the folder was created in the previous test.

Conclusion

We have demonstrated how you can use the DIR function to test whether a file or folder exists and decide what actions you wish to perform depending on the outcome of the test.

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 Check File Exists

Check File Exists Using Excel VBA

VBA Check File Exists helps to Check if file Exists in Location using Excel VBA. After mentioning the file path in the computer what if someone deletes the file or change the folder path of the file, obviously, our code will throw an error in such cases. To resolve this issue we can do one thing before we actually open the file, we can check whether the mentioned file exists or not.

In this article, we will show you how to check whether the particular mentioned file exists or not.

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more

How to Check if File Exists or Not?

  • How excel VBA knows whether the file exists or not??
  • By default, it cannot.
  • So, then how??
  • We need to use the function called “Dir” to check whether the file exists or not.

What does DIR Function Do?

VBA DIR function returns the name of the file name with its extension in the specified folder path. When the folder doesn’t have any file it returns the empty string.

So by using this function, we can actually test whether the file exists or not. Even without DIR function, we can test whether the file exists or not. We will see some of the examples below.

How to Use VBA Check File Exists in Excel?

We will learn how to use a VBA Check File Exists Function with few examples in excel.

Example #1 – VBA Check File Exists

Ok, let’s write some code to test the file exists or not. Follow the below steps to write code on your own.

Step 1: For this go to the VBA window and under the Insert menu select Module as shown below.

Step 2: Start the subprocedure.

Code:

Step 3: Define the variable as String.

Code:

Step 4: Now I want to test the file named as “Chapter-11. InputBoxes.xlsm” in my E-Drive”. I will assign my file path to this variable.

Code:

Step 5: Now define one more variable to apply the DIR function.

Code:

Step 6: Now for the second variable open DIR function.

Code:

Step 7: DIR function requires the file path. Since we have already assigned the file path to the variable “FilePath” we can simply pass this variable to the DIR function.

Code:

Step 8: Now DIR function returns only the File Name as “Chapter-11. InputBoxes” from the mentioned file path. So let’s show the result in a message box.

Code:

Step 9: Now run the macro to see the result.

Since there is a file exists in the mentioned path our DIR function filtered the file name from the huge path.

Step 10: Now I will change the file name to a different thing which is not there in the mentioned path.

Code:

Step 11: If I run the code now it will return an empty string in the message box.

DIR function is best suited to use with IF statement in VBA. Above, we could see only the file name with its extension if exists or else we could only see the empty string.

Example #2 – DIR with IF Condition

Step 1: But using IF statement with DIR function we can alter our results. For an example look at the below code.

Code:

Step 2: Here IF condition checks whether the variable “FileExists” value is nothing (“”) or not. If the variable value is nothing (“”) then it will return the result as “File doesn’t exist in the mentioned path” or else it will return the result as “File exists in the mentioned path”

Below is the example of a screenshot of the same.

By using DIR function, we can check whether the file exists or not.

Recommended Articles

This is a guide to VBA Check File Exists. Here we discuss how to use Excel VBA Check File Exists Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

Ссылка на основную публикацию
Adblock
detector