Link to home
Start Free TrialLog in
Avatar of ict-torquilclark
ict-torquilclark

asked on

Run VBA conditionally on file name

Is there a way to have a macro automatically run if it has a certain file name?
Avatar of RichardSchollar
RichardSchollar
Flag of United Kingdom of Great Britain and Northern Ireland image

You could check to see what the file name inside the Workbook_Open event and then run a piece of code if file name is "X" for example.  Note however, that this relies on the user enabling macros when the workbook is open (as any VBA code relies on the user doing this if their security settings are set to anything other than Low):

Richard
'following code in ThisWorkbook module
 
Private Sub Workbook_Open()
If ThisWorkbook.Name = "YourSpecificFilename.xls" Then 'amend as appropiate
  Call YourSubName  'amend as appropriate
End If
End Sub

Open in new window

Avatar of ict-torquilclark
ict-torquilclark

ASKER

I am unsure weather this will achive what I need it to. The probalem is that every night the spreadsheet in question is overwritten with ther new one. Because the spreadsheet is overwritten does this mean that thre code will not work?

Thanks
If the spreadsheet in question is overwritten by another spreadsheet that does not contain the code, then there will then be no code to execute.  Please could you explain in detail what it is you want to achieve.
I have some statistics software that creates a .xls file every morning at 1:00am. The filepath and filename are always the same each time the file is created (and so the previous spreadsheet is overwritten). I have created a schedualed task to open the spreadhseet at 1:30 am. I have also created some code in the personal maco workbook so it is available each time a new spreadsheet is created to format the data and then email it to the required people. What I need to do is for excel to check the spreadsheet upon it opening and run the code (from the personal macro workbook) if the filename is "stats.xls".

I hape that makes sense.

Please ask if you have any more questions.
Is the computer unattended ie you want the file opening and checking to happen automatically with no user involvement?  Is it Windows Task Scheduler you're using to open the specific file?
The comnputer is unattended. I want to make the process compleatly automated. Windows is using Schedualed tasks (start > all programs > accessories > system tools > schedualed tasks) to open the file.
ASKER CERTIFIED SOLUTION
Avatar of Rory Archibald
Rory Archibald
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That's a simple and neat solution Rorya :-)
Thank you very much RichardSchollar! :)
(why are we being so formal??)
Do I know you?   ;-)

That 'a' on the end was a typo!  No idea how I managed that...