VBA stopping without code telling it to do so - vba

Pretty much the title. The code goes forward until it hits a line, and then acts as though it ran into a Stop command, except there is no such line.
StartDate = DateAdd("d", -1 * NDays + 1, EndDate) 'the immediately preceding line
'NDays is an integer, EndDate is a date
With Excel.Application 'the line that it stops on
.ScreenUpdating = True
.DisplayAlerts = True
.Calculation = xlAutomatic
End With 'I put these here because the next lines save the workbook
'if I put them before the excel.application stuff it asks if I want to save when closing
Why is it stopping on that second line? Does anybody know?

Try it without the with block and see what happens. So something like:
Application.Screenupdating = True
Application.DisplayAlerts = False
Application.Calculation = xlCalculationAutomatic
I am at a loss for the why behind this (and if anyone knows, please do share), but I have encountered issues with instancing new Applications, and as a result the code exhibits the same behavior where it goes to use the new instance and simply shuts off.
If I had to hazard a guess, I would assume it has something to do with how Excel is managing the VBA processes. It is possible (though I could be entirely mistaken) that the new Application process assumes control, and that this causes the first application to (in layman's terms) assume it is finished, and simply quit. That, or it pauses its own process (like a DoEvents command) but can't resume. Again, these are guesses.
Also, why the 'Excel.Application'? Are you creating a new instance called Excel? If you intend to just use the application the code is running in just us 'Application'.

Related

VBA program stops to refresh the worksheet

I'm making my own Conway's Game of Life on VBA where the current state is displayed on a worksheet.
Because I'm not skilled, the implementation is probably not very efficient (I use 2 boolean matrices to model the current state and the next one).
To display the result at each step, I've sub display() that took the matrix_currentand color each cell in black or white. To make the whole process smoother, I've wrapped Application.ScreenUpdating = Falseand Application.ScreenUpdating = True . Short story long, it looks like that :
Private Sub display()
Application.ScreenUpdating = False
For i = 0 To sizeGrid
For j = 0 To sizeGrid
If matrix_curr(i, j) Then
Cells(i + xmin, j + ymin).Interior.ColorIndex = 1
Else
Cells(i + xmin, j + ymin).Interior.ColorIndex = 2
End If
Next
Next
Application.ScreenUpdating = True
End Sub
Before each Call display() I call the method Sleep() to let enought time to watch each step.
So, here is my issue:
The display on the worksheet often stops after a number of steps. However, the programm is still running and finally shows the last state. So basically, I can monitor the beginning, then nothing change until the last step that are displayed.
Everything happen as if the worksheet suddenly stop to be refreshed.
Do you have any idea to solve this issue.
I thank you in advance for your help (and hope that I make myself understood
despite my poor english)
My problem is that after a number of steps, nothing more happen on the screen (as if it was freeze).
That's because Excel is essentially running out of breath - it's basically not keeping up with all the ScreenUpdating toggles.
When you toggle Application.ScreenUpdating back on once, Excel happily responds by repainting itself.
When you're running a busy loop, it's prioritizing execution of the VBA code and the Excel UI goes:
(not responding)
This is normal: there's a lot of things to process, so it's processing them - updating the UI, raising worksheet events, responding to user actions, calculating cells, all these things "drop priority", until the VBA code completes.
Try adding a DoEvents instruction immediately after toggling Application.ScreenUpdating back on; this explicitly tells Excel "okay, go ahead, process whatever other stuff you've got, then come back here when you're ready". I'd warmly recommend leaving Application.EnableEvents off and Application.Calculation set to xlCalculationManual until the code completely executed.

How to stop Excel window from staying on top when macro is running continuously? Application.screenupdating doesn't work

I'm trying to run a VBA macro that updates a Get HTTP response to a cell every second.
When the macro is running and I switch to another program (Chrome for example), the Excel window (and sometimes along with it the VBA editor) pops up and stays on top after a couple of seconds.
I have seen other posts suggesting the use of Application.screenupdating = false, but it doesn't work in my case. I'm using a Mac if that's relevant.
For your info I'm running two subs - first one to get the HTTP response string then call the second sub, and the second sub uses Application.onTime to calculate when to execute the first sub again.
I just want the macro to run in the background whilst I work on other tasks.
UPDATE
It seems the Application.onTime command is stealing focus. I tried to run the following sub as a test and it replicated the problem I've been having.
Sub test()
Application.OnTime Now + 0.01157407 / 1000, "test"
'0.01157407/1000 = 1 second
End Sub
I'm not entirely sure how to test your issue as I've never encountered it. And I cannot simply comment on your post with a suggestion. However, using the following Sub should disable most of Excel's updates, events and alerts.
Do note that it will make excel unusable by the user when it is enabled, and therefore needs to be disabled after calculations.
Public Sub FastApplication(Optional ByVal opt As Boolean = True)
With Application
.Calculation = IIf(opt, xlCalculationManual, xlCalculationAutomatic)
.DisplayAlerts = Not opt
.DisplayStatusBar = Not opt
.EnableAnimations = Not opt
.EnableEvents = Not opt
.ScreenUpdating = Not opt
End With
End Sub

VBA: copy sheet without displaying it for a fraction of a second

I have a macro on sheet "Index" if the macro is clicked I want to create a new sheet and copy in it a part from another sheet (called "Template").
I have the following code that does the job:
Set new_sheet = Sheets.Add(after:=Sheets(Sheets.Count))
Sheets("Template").Range("A1:Z100").Copy
Destination:=Sheets(new_sheet.Name).Range("A1")
ActiveWindow.DisplayGridlines = False
Sheets("Index").Activate
However, I do not like that for a fraction of a second the new sheet is displayed (I find it a little bit disturbing, like a subliminal message). I would like to remain on the "Index" sheet. Hence,
a) is there a way to avoid the newly create sheet is displayed;
b) if the answer to a) is negative, is there a way to show a dialog box that last for a fraction of second like "Elaborating..." that hides what happens in background?
You can set the ScreenUpdating property to True or False to suit your needs with this at the beginning of your Sub:
Application.ScreenUpdating = False
And this at the end:
Application.ScreenUpdating = True
See here for more information.
use
Application.ScreenUpdating = False
somewhere before you do your copy
Fully agree, you can use set the ScreenUpdating property to True or False as everyone has already mentioned. But you need to take caution. If you debug or the app bugs out while screenupdating is set to false, then it will cause the excel file to "freeze" - but not completely, just the screen. As it mentions, the screen does not update until you call it to be true again.
So, I would suggest to leave this out while developing. It can be very annoying to go back and forth to enable it manually in the code each time the program freeze.

ScreenUpdating = False fails in Excel 2013 and 2016

Long-running, high-end Excel-based applications that I developed years ago and that run beautifully in Excel 2007 and 2010 look like Amateur Hour in Excel 2013 and 2016 because Application.ScreenUpdating = False no longer works reliably.
The screen unfreezes apparently when VBA code copies a preformatted worksheet from the macro workbook into a new workbook, although other circumstances must trigger it as well.
I’ve seen the threads on this subject that recommend “fiddling with the code” or “calling the code in a subroutine”. Unfortunately, I have to maintain hundreds of Excel applications each with thousands of lines of code and hundreds of users who are about to migrate to Office 2016, so rewriting is not an option. How can I recover Excel’s former elegance?
I wanted to leave a comment but I am not allowed to do so. Without a code sample it is very dificult to understand your problem (please see https://stackoverflow.com/help/how-to-ask and edit your question appropriately.
Here are some ideas:
- Check if your code calls for code in a different procedure, maybe the Application.ScreenUpdating is turned on outside of the procedure.
- Try this at the beginning of your procedure:
Application.Calculation = xlCalculationManual
Then, at the end of the code set it to:
Application.Calculation = xlCalculationAutomatic
It might help; however, without a code sample it is very difficult to properly help you.
Here is a technique that helps reduce flickering and preserves the StatusBar message.
Application.Cursor = xlWait
Application.ScreenUpdating = False
. . .
Set wkbNewBook = Workbooks.Add
ThisWorkbook.Windows(1).Visible = False
. . .
ThisWorkbook.Windows(1).Visible = True
wkbNewBook.Activate
Application.ScreenUpdating = True
Application.Cursor = xlDefault
We have been dealing with this problem now for a long time as my tools do show live animated charts which all of the sudden were completely static - we would have died for having at least a flickering animation.
Initially we tried to force the animation with a forced screenupdate but that did not work. Just by pure coincidence (copy pasted too many times) we stumbled into a solution which is equally unbelievable as it does seem to work. After each Application.ScreenUpdating = True we have added x3 times DoEvents. On some systems x2 times DoEvents works but x3 times does seem to be more reliable on the various office releases out there. Voila our animation came back :-)
Application.ScreenUpdating = True
DoEvents
DoEvents
DoEvents
We have not used it for the Application.ScreenUpdating = False statement but it might do some magic there. Anyway we hope that this road can help some of you finding creative functional solutions!
After looking through many forums, I believe the flicker problem is related to SDI vs MDI.
Someone suggested setting the application to not visible.
Application.Visible=False
enter code here
Application.Visible=True
This solved my flicker problem, but I didn't like how the excel application disappeared completely then suddenly reappeared for the user.
I was able to solve the issue to my liking by using a workaround this 'which window is on top' problem.
By leaving the main window alone, and forcing other workbooks to become not visible, letting the code run, then bringing them back to visible, it stopped flickering.
Application.Workbooks("yourworkbooktohide").Windows(1).Visible = False
Just remember to bring it back with =true.
Again, my script worked just fine in Excel 2010, but after "upgrading" to 2013, this flicker issue started.
For me, only "Application.ScreenUpdating = False" did not completely cure the flickering.
Calculation caused also the flickering.
Adding "Application.Calculation = xlCalculationManual" solved the flickering issue.
So, the code should be like:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
... inportant code here....
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Nico Mijnster.
I had the same problem and, believe it or not, it was solved by unplugging and reconnecting the cable of my second monitor. This cable is using a HDMI to VGA converter.

Closing a userform that is in workbook A from workbook B

I'm new to VBA so there might be a simple answer to this question but if there is I sure haven't found it. What I am doing is copying data from several workbooks into one master workbook. I have writen the code for this and it works fine. The only problem is the workbooks where I'm retriving the data have userforms that automatically initiate when the workbook is accesed. This means that when I run my code to copy the data it hangs at each userform and wont continue until I've physically closed each userform. So my question is: Is there a way to remotely close the userforms in the raw data workbooks from my master workbook VBA code? Thanks in advance.
to close all userforms, (if you want a specific one , change my code)
sub Close_Userforms()
Dim Form as VBA.Userform 'if not work change to Object
For each Form in VBA.Userform
'can add a condition, like : if Form.name ="Whatever" then
unload Form 'if you don't want to lose the data from the userforms, Form.Hide, and later re-loop and Form.Show
next Form
edit : can also if Typename (Form)="Whatever" then , for the condition
Assuming you mean that the forms pop up when you open the workbooks, disable events before doing so:
Application.Enableevents = False
Workbooks.Open ...
Application.Enableevents = True
for example.
I would suggest trying
Application.EnableEvents = False
Further reading.
Short description: All events (Workbook_Open, Workbook_BeforeSave etc), that usually fires upon opening or closing a workbook, will be ignored.
I have written the following functions to make all macros a bit simpler (and faster). Simply place these functions in a regular module.
Public Function CalcOff()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
End Function
Public Function CalcOn()
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Function
Begin your macro with:
CalcOff
And then end your macro with:
CalcOn
Remember that you need to put "CalcOn" in all places that exits the running macro.
Disabling ScreenUpdating makes the code "run in background" (nothing will be displayed).
Setting Calculation to manual improves the speed of the code, since no calculations will be made when changing data. But it's very important to exit all macros with "CalcOn", otherwise your sheet won't calculate (and that's not funny), and it will look like Excel has frozen (since ScreenUpdating would still be turned off).
However, if you by any chance happen to break a running code without exiting it the proper way (running "CalcOn"), simply close the Excel application and reopen it. Or run a macro that ends with the "CalcOn" code. Or create a new macro with that simple line.