Excel add-in - get workbook name of "thisworkbook" - excel

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

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)
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.

Related

Allow "Mouse Click" event or "switch Excel tab" when a macro is running

I have a macro that extracts data from Microfocus RUMBA Mainframe Display and puts in Excel rows one after the other. I have created a Global Mainframe object and that is used for extraction to Excel. But when the process is running and if user decides to stop the processing he cannot click on Stop button on Excel or go to different tabs to see the data being pasted. He has to clicks like 6 times before tabs are switched or stopped.
I see that DoEvents allows mouse click events in the loop to do things but the code is written in a way that there is a lot of lines with in the loop and a function with no loop, and placing DoEvents after everyline seems irrational. I have a feeling there is a better to do that but not sure what that is. Can anyone please help?.
VBA is single threaded. So you can't have one VBA action interrupt another. If you had a cancel button, for example, and the user was allowed to click it via a DoEvents processing the cancel action would still run after the currently running procedure.
In Excel this single threaded nature ends up being a good thing because you generally don't want the user interacting with the workbook while you are making programmatic changes. If this was allowed you would get undefined behavior.
Your best course of action would be to make a .NET application that uses the Excel Interop extensions to move the data from the mainframe to Excel. If you use VB.NET then you will find the code is quite similar to VBA. In fact, the Excel.Application object model is identical so the macro code you already have ports cleanly over.
There is an add-in that will help RUMBA development here:
https://www.microfocus.com/documentation/rumba/desktop951/RumbaSystemAdminGuide/GUID-DDB7571D-6167-4F8B-876E-E7450F3030B2.html

How can a workbook reopen itself in a separate Excel instance

I want my workbook to open in its own separate instance of Excel. If it gets opened with other workbooks, it should reopen itself in a new instance, perhaps using a code in the Workbook_Open event. Additionally, the workbook should prevent files from opening in the same instance, perhaps by moving them to a new instance or moving itself to a new one. Any ideas will be much appreciated.
Edit:
The purpose of this is that workbooks loaded with code and userforms tend to crash easily causing all other workbooks open in the same instance to crash and lose all unsaved changes and the end user gets frustrated. Another issue is that when the Application.OnKey is used, I experienced three problems: 1. shortcut triggers a code that's usually intended to act on the workbook it resides in. This can be solved by checking whether the hosting workbook is the active workbook before running, but it's better to prevent them from running in the first place. 2. common shortcuts can be reassigned to run a custom code, but usually this shouldn't affect other workbooks. 3. problems happen when multiple workbooks that assign same shortcut to custom subs. the most recently open workbook takes over the shortcut action. Also, when the workbook that contains the shortcut is closed, using the shortcut reopens the workbook automatically, which is not a desired! Removing the custom shortcut doesn't solve the problem of multiple workbooks using same shortcut.
Therefore, best solution is to start such workbooks in their own application instances.
I've had to make an Excel workbook (which was running a timer) reopen itself in another instance of Excel. This was to let the user use the first instance of Excel without the timer interfering. I'm not sure if that's exactly what you need, but that can certainly help you get started. You can find the code on GitHub here.
The procedure that you would be interested in is called OpenItSelfInAnotherInstance and is located in OpenItself.bas.
For it to work you will also need to include the code contained in API_Maximize.bas, API_Sleep.bas and UDF_ExcelIntances.bas. (If you copy-paste, always exclude the line that says :Attribute VB_Name =... since it's there only for when you import the *.bas file in from the VBE)
Please let me know if there is anything unclear in there, so I can add some explanations in my answer if needed.

Can't make Application.DisplayAlerts = False in Excel 2016 VBA

I have been chasing my tail for weeks, with more hours "Googling around than I want to admit.
I have a large, complex analytical app within an Excel 2016 spreadsheet that captures SQL table data, queries email data and does a lot of stuff that I think is pretty cool. Users see sales force automation performance metrics and charts. All is well except for one thing. I cannot stop the "save data?" dialog box from appearing no matter what I do.
As a workaround I've put the spreadsheet on on a network ride and given users a shortcut that runs a VBscript to copy this spreadsheet to a hidden drive on the local PC and runs it. So if they save it, there's no worries as they aren't working with the original data. But as one would easily imagine, the load time is necessarily longer than it need be and users are confused by a message when I am telling them they can't save the data.
Net of a lot of different experiments, it seems like I've uncovered a bug in Excel (yeah, I know, this sounds lame even to me) as I cannot make the Application.DisplayAlerts = False. It just will not take.
See image here:
enter image description here
The image above (or at the above link as I haven't submitted enough question yet to embed images) is obviously taken from the Immediate Window when I was running the app. I entered the steps in the exact order shown. Note that I set Application.DisplayAlerts = False and then checked the value immediately afterwords and it was True.
Very weird. Is this a bug?
One last aside that is probably irrelevant; I was using .XLSB format because of the smaller footprint, much shorter load time and to get around PC setup issues with macros. But I've switched back to .XLSX to simplify the experiment.
To clarify: the code temporarily halts after each single-step in the debugger, resulting in Excel setting it back to True while idle. Here’s a way to verify this behavior:
In the VBE code-development window, open the Immediate window (Ctrl-G).
Temporarily insert the following code somewhere in your routine:
Debug.Print "..."
Application.DisplayAlerts = False
Debug.Print "Application.DisplayAlerts: " & Application.DisplayAlerts
Stop
Using the “Set Next Statement” tool (or Ctrl-F9), set the Debug.Print "..." statement to be the next one to execute.
Run the code form there by pressing F5 (Continue).
You should see this displayed on the Immediate window:
...
Application.DisplayAlerts: False
Now, with the code stopped at the Stop statement, type “?Application.DisplayAlerts” in the Immediate window, and press the [Enter] key. You will get:
?Application.DisplayAlerts
True
because Excel has reset it to True while the code is suspended.
Remove the experimental code.

Workbook_BeforeClose not executing after using VBA editor

As the title suggests, I am having a problem with Excel's Workbook_BeforeClose event handler. I know I am using the correct method signature (shown below) because it has worked in the past, and I have correctly placed the event handler in the "ThisWorkbook" module of the VBA editor. However, I have noticed that whenever I do a significant amount of coding within the VBE (in other modules), this method is not executed. Even when I place breakpoints inside, the breakpoints are not hit before the workbook closes. Again, this only happens if I have been messing around with other modules in the VBE; if I just open the workbook and immediately close it, this method runs fine and the breakpoints get hit. Saving or not saving the workbook does not seem to make a difference, and this problem occurs in Excel 2013 and 2016 (haven't tried opening the workbook in earlier versions). This issue is really starting to impede my workflow, so if anyone has a thought on why my Workbook_BeforeClose handler is not being called, I would very much appreciate the help!
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'More code...
End Sub
After posting this question on the Mr. Excel forum, I was given the solution: Some of the other modules that I was editing contained optimization code. This included disabling Application events while the macro was running, then turning them back on after completion. However, while debugging, I would obviously occasionally stop the macro before it completed, so Application events were never being turned back on!
So now, all I have to do is execute "Application.EnableEvents = True" in the Immediate Window before I try to close the workbook, and my event handler runs fine!

Can't enter break mode at this time

This has been happening increasingly, when I have a sheets.add or sheets.delete in excel VBA. After searching and searching I finally found the official Microsoft support page on it. My question is, does anyone know why I could have stepped through this code just fine over and over, and then all of a sudden it starts doing what Microsoft says it would always do, and is there a way to fix it?
Sub foo()
Sheets.add
debug.print "sheet added" 'breakpoint here
End sub
It's as simple as that. You won't be able to recreate it, because the issue I'm asking about is the fact that it doesn't happen at first. It works just fine over and over then randomly presents the error described in the linked Microsoft support page.
Check if Microsoft Visual Basic for Applications Extensibility is being referenced in the project.
You can check that in the Tools/References Menu on the Visual Basic window of the project.
Referencing Visual Basic for Applications Extensibility prevents the program having its execution suspended:
Excel helps says specifically:
A change was made programmatically to the project using the extensibility (add-in) object model. This prevents the program from having execution suspended. You can continue running, or end execution, but can't suspend execution.
You are unable to step through code when making changes to the project (dynamically eg using InsertLine etc). the code can be run but not stepped through.
Deleting certain objects including ActiveX objects actually changes the VB project. It took me some time to realize that the following line of code prevented the VBE from entering break mode:
Excel.ActiveSheet.DrawingObjects.Delete
If you can identify the code causing the issue, and the order of operations isn't important, move it to the end of your script.
Here are a few suggestions which are not fool-proof,
Firstly, verify that the error does not occur if a breakpoint is not set.
If it doesn't, try a few other things:
From the VBE Debug menu, "Compile VBA Project", it's worth a shot.
Delete the line entirely. Run the code. Then put the line back in and try again with the breakpoint.
Add a DoEvents statement after the Sheets.Add
Use a MsgBox instead of a breakpoint on a Debug.Print. With the message box displayed, attempt to manually break using ctrl+fn+End. (At this point, "breaking" isn't necessary but it would be interesting to see whether you can break this way)
Put a breakpoint on Sheets.Add instead; practically speaking, there's no reason to put the breakpoint on a Print statement if you can just put it on the preceding line.
Are there any Addins? If so, disable all of them and re-enable one at a time, testing to see which one may contribute to the error.
Yet another Excel/VBA glitch.
When it happens to me when I click a button running a macro:
I first try to directly run the macro from VBE,
if it fails, then I put a breakpoint at the first instruction of the macro,
if it still fails, I try both,
or, after clicking the button and breaking on the first breakpoint, I do a single step (SHIFT F8) and then I can let debug run freely as usual (F5).
And so far I don't get this error anymore.
Probably not foolproof either but worth a try.
Ran into the same issue, and (as far as I can tell) the only relevant answer here is Answer 5 (i.e. the one provided by Chrisb).
I've been working with vba for (too many) years now, and never encountered this until I had a project that needed vba to delete ActiveX controls. In my case, the 'ActiveX controls' were a spurious result of data copied in from a web page.
Additionally, there appears to be a way around the issue. Using the following code (versus, e.g. deleting the ActiveX as a shape), seems to circumvent the issue:
On Error Resume Next
ActiveSheet.OLEObjects.Visible = True
ActiveSheet.OLEObjects.Delete
On Error GoTo 0
I say 'appears' and 'seems' above as implementing the above solved the issue for me. However, before I implemented same, I had made other code changes and I have not yet fully regression tested for all possible other reasons the problem was resolved. :)
This has happened to me multiple times and this solution works for me.
Run a different macro within the same VBA project.
Then go back and run the same macro that is causing the pop-up message to appear. The message should no longer appear.

Resources