Sunday, 17 June 2012

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 (Lesson 9).

ThisWorkbook
ThisWorkbook is the workbook within which your VBA procedure runs. So if you write:ThisWorkbook.Save

The workbook within which your VBA procedure (macro) runs will be saved.
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:ThisWorkbook.Saved=True
ThisWorkbook.Close

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":If Dir("C:\Stuff\toto.xls") = "" Then

You could also use a sentence that means "If the file "C:\Stuff\toto.xls" does exist then":
If Dir("C:\Stuff\toto.xls") <> "" Then

If you are looking in the same folder as the file in which the macro runs you can simplify the VBA code:
If Dir("toto.xls") <> "" Then

In google 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,ActiveWorkbookWindowsKill, and many other VBA words to work with one or many workbooks.

No comments:

Post a Comment