All sheets and all modules have Option explicit at the top.
Require variable declaration is ticked
I have just two sections of code, each in its own module.
But Option Explicit is being ignored.
As a test, I put in a new line of code
sausage = 3
and it compiled without error.
I've checked all the possible code sections in the workbook with the code below. It fails compilation in all of them except one. The entire code in that module is:
Option Explicit
Sub SelectPath_Click()
s = 3
End Sub
Using Debug --> Compile VBA project produces no error, and the option to do it again is greyed out afterwards.
The code is as you can guess called when a button is clicked. I THINK the button is a Form control as opposed to an active-x, but I don't know how to query the button to find out what type it is.
There are no active add ins.
In the meantime, I have moved the sub from a Module to the sheet on which the button sits and hey, presto. Compilation fails.
So the question now is, how can this one part of the workbook ignore Option Explicit? Am I doing something wrong?
Try this. It sounds stupid, but it actually repaired that condition for me on multiple occasions from Excel 2003 through (even this morning) on 2016. If it fails, you'll have only spent 30 seconds trying this admittedly bizarre workaround.
Position your cursor after the "t" in Explicit
Type a space (there's a bizarre technical reason for this; just trust me)
Hit enter
Hit left arrow key
Hit delete key
Now the compiler should do what you expected.
This is in case you did everything right, and you KNOW that Option Explicit is simply not working as it should, which is to give a compile error for undeclared variables.
I found a solution by moving the code from a Module, to the worksheet on which the button calling it was located.
Every other code area correctly failed to compile with duff code (Even the other module with a function in it.)
I had to re-assign the code to the button, but now it all works as it should.
But I have no idea why it should have failed before.
Thanks for looking.
Related
Every once in a while, I will find that somehow the Application.EnableEvents property gets set to false, requiring me to manually set it back to true in the VBE's Immediate window. The mystery to me is that it is set to false without a VBA error being thrown. Had an error been thrown, I wouldn't have questioned it as much.
Can any of you help me out with possible causes to this? For now, I have no leads.
Contextual information:
I have not been able to reproduce the error
Nowhere in my code am I changing Application.EnableEvents
All of my code relies exclusively on events, I don't have any UDFs that I call within worksheet cells
From what I remember, the VBE was open every time, so I was probably actively developing at the time of the failure.
Thanks,
Add a watch on Application.EnableEvents, ensure it is global so set Procedure to (All Procedures) and Module (All Modules) . Change the Watch Type to Break When Value Changes
Make sure your code is unlocked. Then run your applciation, the code should should stop on each line when the value changes. This way, you can double check your code acts as intended.
Incidentally, you an use the RAII design pattern to manage these Application settings. The code here uses a RAII design pattern to manage the status bar Essentially the RAII pattern uses a class and utilizes the destructor to reset a setting.
This setting should never change on its own. I would check to see if you have another workbook open that is modifying the setting.
To do this Open the VBA editor (Alt-F11) and see what workbooks are open by looking at the project explorer on the left hand side. Look inside each project for code that is disabling the events.
Also, when you do a search on your project and any other open project, make sure to choose "Current Project" in the find window and search on "EnableEvents" The current project is not selected by default and you may be missing some code in your search you didn't know about like the workbook startup event.
My real motivation for writing this was Macros Not Showing Up in Macro Table. But the macro question is really just a plain vanilla Sub located in a Module file. Literally:
Public Sub LaunchRecognia()
GetRecogniaFactory.GetRecogniaVm(ThisWorkbook).ShowForm
End Sub
Thinking it might be a security issue but I doubt it (see below).
However the only reason I wanted the dialog was just to assign a shortcut key, so thought I might see if anyone knows how to do this in code while I'm at it.
Any ideas to troubleshoot the macros not being available? Code to assign shortcuts?
Turns out this was a corrupted workbook. NO surprise there but the corruption was difficult to detect!
The workbook had a custom ribbon, with a code module to support it. The code module must have been inadvertently deleted. BUT the code still worked, am surmising that the ribbon must somehow embed the code in binary form.
Moved all sheets and code to a new workbook, recreated the missing module, and all's well with visible macros.
Still would love to know if there is a way to programatically assign a key code tho...
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.
When I try to show userform1 with userform1.show in ThisWorkbook within the private sub workbook_open(), it does the strangest thing. (I'm using Excel 2007)- It enters break mode and stops the running of the code!!!
I open the macro enabled workbook and the userform appears as planned, but the when I move the mouse within the area of the userform it enters break mode and highlighting the row UserForm1.Show as if it is the problem.
Furthermore when I press F8 it's highlighting the private sub workbook_open() and another press highlights userform1.show again and another press shows me the run time error '400'.:
application-defined or object-defined error.
This has never happened to me before, I found a post that says it has no answer here.
Any ideas?
I also came across the same scenario.
What I did was to change the ShowModal property in the Form properties to False and the break went away.
I had the same problem, and the answers above didn't fix it. Restarting the PC resolved it temporarily, but after a while the problem returned. After a few frustrating days with a lot of restarting the pc, I came up with these conclusions:
What I think causes the problem is when you use ctrl+break to stop the code while running.
What solves the problem for me is to press ctrl+break while the code is NOT running, it'll show that it's in break-mode, and then press F5. It won't start running, but it will exit break mode again. When you've done this the problem should be fixed and you can run the code as usual.
I guess this method works the same as restarting your pc, but it's a lot faster.
It's an odd behaviour I already faced some times when dev'ing... some tips that might help you out:
Compile the code
Clear all breakpoints
Check project references (missing references may cause problems)
Add some unnecessary statement (like if 1 = 2 then DoEvents) before the 'hidden breakpoint', compile the code and then remove the code again
Install & run VBA Code Cleaner
Either way, that's a mystery for me the cause of this odd issue. It seems that somehow some breakpoints are kept in the memory even after removing them...
Hope it helps!
First thing to try is to recompile your VBA project and then save the workbook containing the macro. If compiling throws up an error you will probably get more information from the compiler message such as a missing reference.
Also make sure that you cleared all previously existing breakpoints. It might be the case that you first have to create a new breakpoint (F9) and then clear all breakpoints (Ctrl+Shift+F9) for the command to be enabled.
From what I can see on the web, this is a fairly common complaint, but answers seem to be rarer. The problem is this:
We have a number of Excel VBA apps which work perfectly on a number of users' machines. However on one machine they stop on certain lines of code. It is always the same lines, but those lines seem to have nothing in common with one another.
If you press F5 (run) after the halt, the app continues, so it's almost like a break point has been added. We've tried selecting 'remove all breaks' from the menu and even adding a break and removing it again.
We've had this issue with single apps before and we've 'bodged' it by cutting code out of modules, compiling and then pasting it back in etc.
The problem now seems to relate to Excel itself rather than a single .xls, so we're a little unsure how to manage this.
Any help would be gratefully received :)
Thanks,
Philip Whittington
I have found a 2nd solution.
Press "Debug" button in the popup.
Press Ctrl+Pause|Break twice.
Hit the play button to continue.
Save the file after completion.
One solution is here:
The solution for this problem is to add the line of code
“Application.EnableCancelKey = xlDisabled” in the first line of your
macro.. This will fix the problem and you will be able to execute the macro
successfully without getting the error message “Code execution has been interrupted”.
But, after I inserted this line of code, I was not able to use Ctrl+Break any more. So it works but not greatly.
This problem comes from a strange quirk within Office/Windows.
After developing the same piece of VBA code and running it hundreds of times (literally) over the last couple days I ran into this problem just now. The only thing that has been different is that just prior to experiencing this perplexing problem I accidentally ended the execution of the VBA code with an unorthodox method.
I cleaned out all temp files, rebooted, etc... When I ran the code again after all of this I still got the issue - before I entered the first loop. It makes sense that "press "Debug" button in the popup, then press twice [Ctrl+Break] and after this can continue without stops" because something in the combination of Office/Windows has not released the execution. It is stuck.
The redundant Ctrl+Break action probably resolves the lingering execution.
I found hitting ctrl+break while the macro wasn't running fixed the problem.
I would try the usual remedial things:
- Run Rob Bovey's VBA Code Cleaner on your VBA Code
- remove all addins on the users PC, particularly COM and .NET addins
- Delete all the users .EXD files (MSoft Update incompatibilities)
- Run Excel Detect & Repair on the users system
- check the size of the user's .xlb file (should be 20-30K)
- Reboot then delete all the users Temp files
I have came across this issue few times during the development of one complex Excel VBA app. Sometimes Excel started to break VBA object quite randomly. And the only remedy was to reboot machine. After reboot, Excel usually started to act normally.
Soon I have found out that possible solution to this issue is to hit CTRL+Break once when macro is NOT running. Maybe this can help to you too.
Thanks to everyone for their input. This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office's native COM components and does stuff that REINSTALL doesn't. I expect the latter just goes through a checklist and sometimes accepts what's there if it's already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user's machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.
I have had this problem also using excel 2007 with a foobar.xlsm (macro enabled ) workbook which would get the "Code execution has been interrupted" by simply trying to close the workbook on the red X in the right corner with no macros running at all, or any "initialize" form, workbook, or workheet macros either. The options I got were "End" or "Continue", Debug was always greyed out. I did as a previous poster suggested Control Panel->Programs and Features-> right click "Microsoft Office Proffesional 2007" (in my case) ->change->repair.
This resolved the problem for me.
I might add this happened soon after a MS update and I also found an addin in Excel called "Team Foundation" from Microsoft which I certainly didnt install voluntarily
I would like to add more details to Stan's answer #2 for below reasons:
I faced this issue myself more than dozen times and depending on project conditions, I chose between stan's voodoo magic answer #1 or #2. When I kept on facing it again, I become more inquistive that why it happens in first place.
I'd like to add answer for Mac users too.
There are limitations with both these possible answers:
if the code is protected (and you don't know password) then answer #1 won't help.
if the code is unprotected then answer #2 won't let you debug the code.
It may happen due to any of the below reasons:
Operating system not allocating system resources to the Excel process. (Solution: One needs to just start the operating system - success rate is very low but has known to work many times)
P-code is the intermediate code that was used in Visual Basic (before .NET) and hence it is still used in the VBA. It enabled a more compact executable at the expense of slower execution. Why I am talking about p-code? Because it gets corrupted sometimes between multiple executions and large files or just due to installation of the software (Excel) went corrupt somewhere. When p-code corrupts. the code execution keeps getting interrupted. Solution: In these cases, it is assumed that your code has started to corrupt and chances in future are that your Excel workbook also get corrupt giving you messages like "excel file corrupted and cannot be opened". Hence, as a quick solution, you can rely on answer #1 or answer #2 as per your requirements. However, never ignore the signs of corruption. It's better to copy your code modules in notepad, delete the modules, save & close the workbook, close the excel. Now, re-open the workbook and start creating new modules with the code copied earlier to notepad.
Mac users, try any of the below option and of them will definitely work depending on your system architecture i.e. OS and Office version
Ctrl + Pause
Ctrl + ScrLk
Esc + Esc (Press twice consecutively)
You will be put into break mode using the above key combinations as the macro suspends execution immediately finishing the current task. This is replacement of Step 2.
Solution: To overcome the limitation of using answer #1 and answer #2, I use xlErrorHandler along with Resume statement in the Error Handler if the error code is 18. Then, the interrupt is sent to the running procedure as an error, trappable by an error handler set up with an On Error GoTo statement. The trappable error code is 18. The current procedure is interrupted, and the user can debug or end the procedure. Microsoft gives caution that do not use this if your error handler has resume statement else your error handler always returns to the same statement. That's exactly we want in unwanted meaningless interruptions of code execution.
My current reputation does not yet allow to post this as a comment.
Stans solution to enter the debug mode, press twice Ctrl+Break, play on, save did solve my problem, but I have two unexpected twists:
My project struture is password protected, so in order to get into the Debug Mode I had to first enter Developer mode, click on the project structure and enter the password.
My project is a template file (.xmtl). I opened the file via double click which opens it as .xml with a "1" at the end of the previous file name. I fixed the bug as by Stans instruction and saved it as that ...1.xml file. When I then opened the template again, this time as template, and wanted to apply the same bug fix to that file, the bug was gone! I did not change this file and still no bug at executing the Macro. This means to me that the bug is not actually in the file, but in a (hidden) setting in Excel.
If it's a phantom breakpoint:
1 Delete the offending line of code
2 Run the code again
3 Repaste the line
I found this laughably simple solution after spending a couple days wading through all the answers here and elsewhere. I figured, if I link it to my original question it might help some other poor chap, since the question it's on is VBA break execution when there's no break key on keyboard and this is more applicable.
Link to original answer
I faced the same issue today. Resolved it with these steps.
Create a new module
Move the procedure that is causing the issue to this new module.
Save project
Run macro again.
This time, the code execution will run till completion without any intermediate stops.