VBA Lesson 14: VBA for Excel for Workbooks
To develop a VBA procedure that is triggered by an event relating to the workbook (when you open it, when you save it, when you close it) see the VBA lesson on events.
ThisWorkbook is the workbook within which your VBA procedure runs. So if you write:
If you want to close the workbook within which your VBA procedure (macro) runs without saving it you will write these two lines of code:
Verifying the existence of a file
When you want to verify if a certain file exists on your disk you will use the following code that means "If the file "C:\Stuff\toto.xls" does not exist then":
You could also use a sentence that means "If the file "C:\Stuff\toto.xls" does exist then":
If you are looking in the same folder as the file in which the macro runs you can simplify the VBA code:
In the downloadable tutorial on Excel macros you will find many other uses for Dir including opening all the files of a folder to generate a consolidated database (whatever the number of files in the folder). You will also learn about Path, ActiveWorkbook, Windows, Kill, and many other VBA words to work with one or many workbooks.
We hope you have enjoyed this
Go to the next lesson