How to force excel to gain focus and refresh the UI - excel

When I run a series of macros eventually excel loses focus and stops updating the screen this can occur looking at the screen or especially minimizing and doing something else on the computer. It can only be fixed by double clicking somewhere scrolling around maximizing and minimizing... but I can't seem to accomplish it in VBA I would hate to have to make an external macro to click into excel just to make the screen refresh.

Are you asking to see everything happen or do you want to just let it run and come back to it? You can use the code Application.ScreenUpdating = False to prevent the crazy jumping excel does and just come back as normal.

Related

VBA Excel - Stop user from being able to use the mouse but allow the user to stop or pause the script

Good afternoon everyone.
*Note- I have looked for a couple of days for the answer to this question.
I have a bit of code that controls a separate piece of software to enter data.
I can not access the scripting side of this software, so I will just leave that bit out.
I have the following working.
Mouse movement.
Mouse Click.
Data input.
The only problem here is that while the script is running, I can still move the mouse manually. Which in turn can cause it to click on something wrong.
I know that
"BlockInput = True" deactivates mouse and keyboard.
This stops me from using the keyboard or it would work great.
"Application.Interactive = False" makes the cursor do the thinking thing.
This stops the program from clicking on the items I need to be clicked and still lets me use the mouse.
I hope this makes sense. This script will only be temporary until I get scripting access to the software.
Thank you in advance.

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.

Enable button using VBA excel

I have an uncommon issue. I have an Excel file with macros. On all computers it was installed Office 2010 and everything worked fine, but a few days ago every computer was upgraded to Office 2013.
In code, at some point I enable or disable some buttons based on some criterias.
ThisWorkbook.Worksheets("Lab Orders").OLEObjects("CommandButton1").Enabled = False
On some computers this works fine , but on other computers this button is shown as enabled, and if the user clicks the button nothing happens, not even the animation where the the button is pressed, so it cannot execute the code behind. It's like an image. Any leads, or reasons why this is happening only on certain computers ?
I have this problem after the Office got upgraded. PS. All computers are in the same domain.
LATER EDIT
I changed the code line
ThisWorkbook.Worksheets("Lab Orders").CommandButton1.Enabled = True
and now I get this error: 438 at this row (I debbuged the file on a computer where this file does not work)
I suspect it's the issue with the latest Office updates - see if this fixes it: http://excelmatters.com/2014/12/10/office-update-breaks-activex-controls/
On all computers where you have the problem, check the box "Trust access to the VBA project object model" located in Options/Trust Center/Macro Settings
(Note that this will only apply to Excel, and if you are having the same problems on other MS Office softwares, you should do the same on them as well)
If that's still not working, read and apply all the checks on this page : https://support.office.com/en-gb/article/Enable-or-disable-macros-in-Office-files-12b036fd-d140-4e74-b45e-16fed1a7e5c6
Did not fit as a comment, so:
If I understand you correctly, some computers show the button enabled, while in fact it is disabled, right?
In this case it's normal no button press animation "visibly happens" as Windows knows the button was programmatically disabled.
The same thing happens if you hook a window (which has buttons on it) and send any button a WM to show itself as if it was enabled (while in fact it is not).
The reason it seems enabled on some computers may vary, most probably it's video card and/or driver 'issue', or some "strange alignment" (that particular OS with that particular graphics card & driver and DirectX, as well as those 'special' OLE settings, etc).In both cases, the screen area don't get "refreshed" (invalidated) after the button was disabled - so it seems enabled and gets "repainted" only when there was some user interaction around it. "Lazy redraw", so to speak :)
What one can do is, if it happens to be a serious issue, to find a way on one of these computers to get the button visibly disabled with some 'workaround' (e.g. changing button text after it was disabled -maybe even to exactly the same text-, or move it 1 pixel away and back, call InvalidateRect on it, etc), and apply that solution to your Excel macro.
UPDATE after reading asker's comment:
Oh I see. This could happen if the buttons are in a control array. The issue in this case, however should be present on all computers... Strange.
Anyway. Try to test the buttons' Index property to see if they are part of a control array, just to be sure. If yes:
a) remove them from the array and create buttons "independent" from each other
b) create a bool array and store there enabled/disabled status and write a function that updates buttons' text color property & handles button click event ignore/accept

VBA Form disappearing

I have a VBA form that when I click on it, performs some long calculations (a few seconds to several seconds long) and then displays the results on frames in the form. However, once every so often, the form hides on me and I need to click around to the VBA editor and back to the sheet to make it display again
I have
Me.Repaint
at the end of the calculations on the form
but it still doesn't help
I also tried disabling the "EnableCalculation" attribute of the main sheet, but still no use
Anyone ever run into something like this? Do I need to load the form in some special way?
I have had the same problem. When saving an Excel workbook by clicking on a command button on a modeless Userform, the form disappears as the code completes.
I read that the problem was due to some inter-compatible changes that Microsoft has made and found some very elaborate solutions involving a lot of complex code that I was unable to integrate into my project. However, I did find a very quick workaround.
In my case the Userform only disappeared when the code executed the End Sub command of the command button's code. I simply added an Exit Sub immediately before it and the Userform no longer disappears.
Have you tried turning off and on screen updating so Excel is not redrawing the screen with each change.
sub doSomthing()
Application.ScreenUpdating = False
'do something
Application.ScreenUpdating = True
end sub
The form disappears because Microsoft has changed the model by which forms are owned by a 'superior' process (Excel in your case). I have the same problem and also cannot overcome it.
Just sit tight until Microsoft decides that it is worth their effort to fix yet another introduced and untested problem by making changes to something that already worked.
The problem is a side effect of the SDI (Single Document Interface) that was introduced with Excel 2013. The various suggestions that invoke DoEvents, ScreenUpdating, etc. may help in certain scenarios, but they do not cure the behavior.
There is a full solution posted here: Keeping Userforms on top of SDI windows in Excel 2013 and up
If that is too involved for your needs, a quick-and-dirty solution is to minimize and restore the active window, which forces the userform back on top of the stack.
'Do long-winded process first, then:
Application.ScreenUpdating = False
ActiveWindow.WindowState = xlMinimized
ActiveWindow.WindowState = xlNormal
Application.ScreenUpdating = True
This doesn't prevent the form from disappearing, but it makes it reappear the end of the process.
Try experimenting with the following two lines of code instead of the repaint.
Me.Show
And/Or:
Me.SetFocus
Hopefully, one of these will work for you!
In my case I had to use all these to make it happen. (frmGUI is my form)
DoEvents
frmGUI.Repaint
frmGUI.Show
With Office 2013 and Windows 7, simply adding DoEvents right before the end of the sub (where the form disappeared) kept the form open. Nothing else needed....for my situation.

VBA editor auto-deletes spaces at the ends of lines

Is there a way to convince the VBA editor in Excel to stop auto-formatting lines to remove the space at the end when I pause in my typing for a quarter second?
I had this exact problem and the following worked for me.
Click the Microsoft Office Button, and then click Excel Options
Click the Add-Ins category
In the Manage box, click COM Add-ins, and then click Go.
Look for an add in called 'Load Test Report AddIn' then uncheck it
restart excel
This addin is installed with VS2010 Beta2
In Excel 2010, toggling Design Mode button on the Developer Ribbon Tab solves the problem for me.
I've definitely had that issue before, where the vba editor would format as I was typing (not just when I went to another line). For me, it seemed to be related to a Microsoft Web Browser control that I had in an open workbook. When I took out the web browser, the VBA editor started acting normally again. I have no idea why that worked, but it did. Now I avoid using that control in my workbooks.
Something is causing your spreadsheet to recalculate while you are in the VBA Editor and this 'compiles' your code and thus strips the spaces. You need to stop the cells recalculating while you are editing. Turning the calculation to manual in the spreadsheet.
Tools > Options > Calculation should do the trick.
I noticed this when I had cells recalculating thanks to a DDE connection.
There is sort of a way to turn off the auto-"correction" in the VBA Editor.
Tools Menu -> Options -> Editor Tab -> Clear the Auto Syntax Check box
Sadly, this won't solve all your problems, as the VBA Editor tends to have a mind of its own, for better or worse.
Taking it out of design mode fixes it every-time on vba2003 - its was driving me crazy at first ... i did notice it might have something to do with the web control but when i take it out of design mode it works fine ... just toggle that to get it to behave :)
I have had this same problem several times recently, and has driven me crazy.
After reading this post all the different fix-ups mentioned (none worked for me), I recalled I have been playing lately with Internet Explorer Control, opening Internet Explorer from VBA.
This is mentioned in some of the answers in this post.
This got me in the right path and, in order to fix it, I had to first delete all iexplore.exe instances (alt+control+delete), closed Excel and open excel again.
(iexplore.exe had been opened invisible from the VBA code, and I didn't know they were running)
That fixed the bug.
I have been programming quite heavily with VBA for over 4 years, and never had this problem.
Just a couple of weeks ago I started using IE control, and I started getting this problem...so in my case I can only assume the bug is directly related to the IE control.
I am running both excel 2003 and 2007 in same PC at the same time, and the problem only happens with excel 2007.
None of the above for me.
I had a Application.OnTime timer that fired every second and this triggered a recalculation of something: commenting it made my day.
This has started happening to me recently after adding a Timer event to an Access 2007 form. The VB editor "finalizes" the current line (as if you had moved the cursor off of the statement; I have auto syntax checking off) each time the event fires (initially I had it set to 1 second, now it is set to 5 seconds, and the behavior scales accordingly). In order for the event code to execute, the application has to ensure that it has been compiled. Presumably, the editor needs to be in a "sane" state to do this, as it probably has to check for code dependencies among modules. Note that the behavior occurs regardless of whether any dependent code is actually loaded into the editor at the time. Note also that resetting the execution state doesn't affect the timer event firing. As a practical matter, one could close the triggering form, switch it to design view, set a breakpoint in the triggered code, or increase the timer interval while working with the editor.
In contrast to abhishek's comment, changing the settings of Tools/Options.../General/Compile On Demand and/or Background Compile did not affect the issue.
If it helps, none of the previous answers solved mine. Only solution appeared to be to close the xls file and reopen it. Frustrating to have to do every 30 mins but at least it works. Would love to know why it's recompiling and cleaning the text... should really be an option to disable the text cleanup but couldn't find it.
Turn off Tools > Options > General > Background Compile. This solved it for me.
This is a long standing problem that could have various causes. I had this same issue occur in the Access VBE (so naturally the Excel answers weren't relevant). After a LOT of digging I finally got it fixed with the solution below. First a recap though:
If you are here because of this issue in Excel, try the solutions above first. To summarize:
The most common issue in Excel is that the Design button is toggled. Toggle that and see if the behavior changes as submitted by Dmitry Frenkel above
If that doesn't work, check for the "Load Test Report" AddIn as mentioned by Ade.
Those are really the two main causes in Excel, but if neither of those solutions work, then scroll through the rest of the solutions here. All are valid possibilities for the cause. In Access the cause is pretty straight forward. It's a timer issue on a form somewhere. I found this solution from here by User Kevin K. Sullivan.
Copy the following line of code onto the clipboard. (You might need to
paste it into a text editor first and coerce it onto one line, depending on
your newsreader. It must be one line.)
For i = 0 to Forms.Count -1: Debug.Print Forms(i).Name, Forms(i).TimerInterval: Next i
Switch to Access.
Press Ctrl-G to go to the Immediate Window.
Press Ctrl-V to paste in the code.
Press enter to to run the code. All open forms will be listed. Any non-zero timer intervals are your culprits. Simply close that form (It may be invisibly open from another process than the one you thought you were dealing with).
I think the solution for Access here is what the user Dom was trying to say above. I guess the down votes were because it wasn't explained very well and/or because he was speaking of Access when the OG issue was in Excel. Regardless, he is likely on point if you are here because of the VBE in Access.
I hope this helps people. I know I kept finding this page when researching this issue, so that's why I thought I'd update this solution here.
I hit this problem today on a fresh install of Excel 2010 Beta 2. None of the above made any difference, but going into the trust center and disabling all application add-ins fixed the problem for me.
I have Office 2010 Pro and I had the same issue. As I type the space between each word was being deleted. After trying each of the options turning them on and off the only way I found working was to disable the Winzip Courie(excel) add-in. This is done thru the Options dialog box Add-Ins section.
In office 365 I had the same issue - what worked for me is I saved the file with a different name and when I re-opened the new file the problem went away.
I found this issue pops up when I had AutoSave on. Turning that off let me code without it compiling every second.
I don't think I've ever seen the VBE remove a space when I've stopped typing. It will remove trailling spaces from lines if you move to another line, but that's something different and not behaviour that I think can be altered.
The removal of spaces in the VBA editor for Access occurs when a form is open in Form("Execute") mode. This is probably due to background executions based on "On Timer" methods. Close the form in Access solves the problem in VBA.

Resources