1

I can't get the name of the workbook when I use a add-in.

I'm trying to develop a add-in that runs each time you open Excel and reads the filename of the open file.

If the file name is XCFIL.SKV then do something...

This code should do it, but it doesn't. What am I missing?
The code stops and if I debug and press F8 it works fine, but it won't run on it's own.

Private Sub Workbook_Open()
    If ThisWorkbook.Name = "XCFIL.SKV" Then
        MsgBox "y"
    End If

End Sub
Community
  • 1
  • 1
Andreas
  • 23,610
  • 6
  • 30
  • 62
  • 3
    [Difference between Thisworkbook.name and Activeworkbook.name in VBA](http://stackoverflow.com/questions/35426907/difference-between-thisworkbook-name-and-activeworkbook-name-in-vba/35426954) – Axel Richter Nov 10 '16 at 13:48
  • Does not solve the problem. Get error 91. Says something about withblock, not sure how to translate it to english – Andreas Nov 10 '16 at 14:00
  • It works either way with thisworkbook, or activeworkbook if I accept the "wait" the error does. But it does not run on it's own – Andreas Nov 10 '16 at 14:01
  • Sorry to ask but are you sure your Workbook is called XCFIL.SKV, because if not it might be running but you would never know...? – Tim Wilkinson Nov 10 '16 at 14:23
  • If that code is in an add-in, it only runs when the add-in is opened - which will be *before* any workbook is active. – Rory Nov 10 '16 at 14:24
  • It is called XCFIL.SKV. I'm sure. As I said, if I let the error happen and debug the code will run as it should. @Rory How do I solve that? – Andreas Nov 10 '16 at 14:26
  • You need to use application events to trap the opening of other workbooks. – Rory Nov 10 '16 at 14:28

1 Answers1

2

Background:
Based in this statement The code stops and if I debug and press F8 it works fine, but it won't run on it's own. I assume the problem relies on the speed of the processor that is not sync with the code (own experience).
Solution:

Since it is Excel and the problem seems to rely only in the opening of the instance itself, you may use Application wait or any of the other functions for this matter.
Further thoughts:

Life cycle comes to my mind in these kind of scenarios. This web page has a neat Lifecycle diagram of excel instance (attached since I will try to explain the scenario)

enter image description here

As you may see "Application" is the first cycle of the Excel application, followed by "Open" and after that "Workbook" object, it may happen that in this life cycle "worbook" has not been created when "Open" comes to play,hence, you need to wait until excel solves this.

Community
  • 1
  • 1
Sgdva
  • 2,800
  • 3
  • 17
  • 28