Stepping through with F8 the code runs, stops in standard execution with F5 - excel

I've written a macro which sums numbers, grouping by year and by month based on our projection model.
It runs from start to end when stepping through with F8.
It stops immediately in standard execution with F5.
The first trouble is
Runtime error 91
in
issmIndex = Range("A1:Z1").Find("ck.IssMon").Column 'issmIndex an integer
Originally I tried Application.WorksheetFunction.Match(...) but had the same problem: runs in debug, but not in execute (Error 1004 instead).
I considered it could have been an Excel version issue (the Match function has a different name in the Italian version). I switched to a more neutral Find, but still no luck.

When you have an error with a line that is a combination of several commands, try breaking it down into the individual steps.
For example, this works:
Sub findDemo()
Const toFind = "blah"
Dim rg As Range, f As Range
Set rg = Range("A2:C5")
Set f = rg.Find(toFind)
If f Is Nothing Then
Stop 'not found
Else
Debug.Print "found in column #" & f.Column
End If
End Sub
Also see the example in the documentation for Range.Find().

Welcome to SO. Sometimes Excel reads code faster than executing, so when reading a command there is a previous one not finished. IT's weird but it happens a lot if your code does a lot of stuff and calculus.
Besides, when debugging, every command line is executed before reading next one, so you cannot detect this just debugging.
So if your code runs perfect when debugged but errors if executed as normal, try to add the command DoEvents right before the problematic line. Something like this:
' your previous code
'
'
'
Doevents
issmIndex = Range("A1:Z1").Find("ck.IssMon").Column 'issmIndex an integer
'
'rest of your code
This commands forces Excel to make sure everything has been executed before reading. It's kind of like a checkpoint, something like make sure you've done everything before going to next line.
DoEvents
function

Related

My vba code closes a document before the print command can be executed

The code I am trying to run is in excel vba and its supposed to open a word document print it and then close the document. For some reason it seems that the code doesn't finish sending the document to the printer and yet it still closes. So the code runs to completion and doesn't generate an error message but nothing manages to print.
When I run the code step by step the document does manage to print. I tried adding: Application.Wait(Now + TimeValue("0:00:05")) to give it time to work. I tried a another form of that line in case the program was telling word to wait instead of excel: Excel.Application.Wait(Now + TimeValue("0:00:05")). I've also tried playing around with the time making it wait 10 second instead of 5.
Any help would be great
If ENG28 = "" Then
Else
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(ENG28)
objWord.Visible = True
objDoc.PrintOut
Application.Wait(Now + TimeValue("0:00:05"))
objWord.Quit 0
End If
I see that you made use of the .Wait method however there is a better way as you can never guarantee that your document is in a printed state within the 5-10 seconds threshold.
The PrintOut method basically has an argument you may add named Background. The default value of this argument is True which would mean that printing occurs in the background and the code continues to run which is causing your file to close before completing the print function. In this case, if you set the Background argument value to False, the macro will not take any more instructions until the printing is done.
try changing the PrinOut line to the following, see if that helps:
objDoc.PrintOut Background:=False

Automatically run VBA macro without a message box

I have an Excel macro that I would like to run automatically when the file is opened. The only way I have gotten this to work is by adding a msgbox before calling to my subroutines. However, this requires me to click OK or close the box for the macros to run. I have tried using a timed msgbox sub, but this also does not work.
For some reason, the msgbox pops up before Excel is fully opened, at which point the macro gets stuck here (code for this is below). From here, I tried waiting for the file itself to be opened until it is in write-mode (Workbook.ReadOnly = false). This also did not work.
Public Sub msgBoxTimer()
Const timeout = 2
Dim objShell As Object
Set objShell = CreateObject("WScript.Shell")
objShell.Popup "Measurement will begin shortly", timeout
End Sub
Private Sub Workbook_Open()
Call msgBoxTimer
Call init ' initiate device
Call updateIndex ' collect & record measurements
End Sub
I get from your comment that you are probably running other shell commands in init and updateIndex.
What needs to be clear is that when you execute a Shell command via a Shell object in VBA, the default behavior is not to wait for the shell command to complete before running the next line of codes.
If you want Excel to wait for the Shell command to be completed before continuing, you can have a look at the answers to this question.
That being say, if you want Excel to be fully open before running any shell commands, you can use a MsgBox like you originally intended, but it has to be VBA's MsgBox that you would simply call like this:
MsgBox "Measurement will begin shortly"
The VBA thread will wait for the "OK" button to be pressed before continuing the execution.

Consistently receiving user input through a long-running procedure (DoEvents or otherwise)

Cleanly cancelling a long API-Ridden procedure is hellish, and I'm attempting to work out the best way to navigate the hellishness.
I'm using excel 2016 (with manual calculations and no screen updates) - I may take some time to attempt to run the procedure on 2010 to see if any issues resolve in the coming days (I'm aware of the slowdowns).
Over time, my procedure LongProcedure has lost its ability to successfully use its cancel feature (presumably due to increasing complexity). It was initially inconsistent and required significant spam-clicking to cancel, and now it fails altogether
Here's the setup:
First, LongProcedure is in a class module LongClass with a public property checked against for early cancelling, allowing it to clean up.
Public Sub LongProcedure()
' [Set up some things] '
For Each ' [Item In Some Large Collection (Est. 300 Items)] '
' [Some Code (ETA 5 Seconds) Sprinkled with 3-4 DoEvents] '
' [Export workbook (ETA 10 Seconds)] '
If (cancelLongProcedure) Then Exit For
Next
' [Clean up some things] '
GeneratorForm.Reset ' Let the UserForm know we're finished
End Sub
Second, I have a UserForm shown from a macro, which instantiates the procedure class, and runs the procedure. It contains a run button, a status label, and a cancel button.
Private MyLong As LongClass
Public Sub ButtonRunLongProcedure_Click()
Set myLong = New LongClass
myLong.LongProcedure()
End Sub
So the issue overall is twofold.
The ExportAsFixedFormat call opens a "Publishing..." progress bar which freezes excel for around ten seconds - fine. In all of my efforts, I haven't found a single way to process user input while this is happening.
On top of this, the DoEvents calls seemingly no longer do anything to allow the cancel button to be clicked. The process inconsistently freezes excel, tabs into other open programs, and (when not freezing) updates the status label.
I've Tried:
Appending DoEvents to the SetStatusLabel method instead of sprinkling - while the form still often freezes, it otherwise updates the status label consistently (while still not allowing the cancel button)
Using winAPI Sleep in place of, and in addition to DoEvents with delays of 1, 5, 10, 50, and 250ms - The form simply stopped updating at all without doevents, and with both it froze more.
Using a Do While loop to run DoEvents constantly for one second (Froze)
Overriding QueryClose to cancel the form. This one helped significantly. For some reason, the close [x] button can be clicked far more consistently than the userform buttons - Still not as consistently as I'd like. The problem? during publishing, Excel stops responding, and as such, modern windows will end the process if you click the close button twice... without cleanup.
Using Application.OnTime to regularly call DoEvents. Didn't seem to improve the situation overall
Alt-Tabbing. No, really. for some reason, while alt-tabbing occasionally just makes the UserForm freeze harder, sometimes it makes it stop freezing and update.
This is an issue I'm willing to do significant refactor work for, including smashing up the idea of the long procedure into separate methods, performing setup initially, and cleanup on class termination. I'm looking for something that provides consistent results. - I'll accept anything from excel versions to excel settings to refactors to winAPI calls.
Thanks for any insight into this one.
As it turns out simply combining together some of the useful improvements, along with a new one, made all the difference.
QueryClose is up to personal preference. Leave it in to catch more terminations, leave it out to ensure users use the new solution
Stick to sprinkling doEvents in places you feel are logical (not just when the status bar updates - like before and after an Application.Calculate call)
Optimize the long-running process as best you can, avoiding excel calls
And, most significantly
The integrated cancel key feature (CTRL+Break by default) is significantly more responsive than UserForm buttons and the form close button, without the chance of accidentally ending the excel task.
Here's the process to polish that for a finished product
First, set up a debugMode, or the inverse handleErrors, module-level variable to control whether to implement break-to-cancel and error handling. (Error handling will make your code harder to debug, so you'll appreciate the switch)
If your process is handling errors, you'll set Application.EnableCancelKey to xlErrorHandler, and On Error GoTo [ErrorHandlingLabel]. The error handling label should be directly before cleanup, and immediately set EnableCancelKey to xlDisabled to avoid bugs. Your handler should check the stored Err.Number and act accordingly, before continuing on to the cleanup steps.
Ensure that if you defer to any other complex vba in your script (such as using Application.Calculate on a sheet with UDFs), you set On Error GoTo 0 beforehand, and On Error GoTo [ErrorHandlingLabel] after, to avoid catching cellbound errors.
Unfortunately, the drawback is that for the UX to be consistently readable, you'll have to leave the cancel key on xlDisabled until the form is closed.
And in code:
Public Sub LongProcedure()
If handleErrors Then
On Error GoTo ErrorHandler
Application.EnableCancelKey = xlErrorHandler
End If
' [Set up some things] '
For Each ' [Item In Some Large Collection (Est. 300 Items)] '
' [Some Code (ETA 5 Seconds) Sprinkled with 3-4 DoEvents] '
' [Export workbook (ETA 10 Seconds)] '
Next
ErrorHandler:
If handleErrors Then
Application.EnableCancelKey = xlDisabled
If (Err.Number <> 0 And Err.Number <> 18) Then
MsgBox Err.Description, vbOKOnly, "Error " & CStr(Err.Number)
End If
Err.Clear
On Error GoTo 0
End If
' [Clean up some things] '
GeneratorForm.Reset ' Let the UserForm know we're finished
End Sub
and in the UserForm
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If MyLong.handleErrors Then Application.EnableCancelKey = xlInterrupt
End Sub
A small note that this method will likely generate a few bugs you weren't expecting to encounter because the execution jumps directly to the specified label. Your cleanup code will need to have required variables instantiated from the start.
Overall, once these issues are fixed, this setup ensures that the user can click CTRL+Break as many times as they could possibly want without causing crashes or popups.

Excel Timer Function Throwing "Expected Function or variable" Error

I have an Excel macro I've called for years I need a pause in running code. Here's the macro:
Sub timeFrame(PauseTime As Double)
'
Dim Start As Double
Start = timer
Do
DoEvents
Loop Until (timer - Start) >= PauseTime
End Sub
I just ran a macro that calls the one above and got an "Expected Function or variable" compile error with the Start = time line highlighted. In troubleshooting, I established that the error occurs with any macro that contains the same line. I even went to MSDN and copied their sample code, and got the same error when I tried to run it.
I thought I might have a missing library reference but nothing showed up there. After an hour or so of Googling I'm at a complete loss for a reason for the error, and would greatly appreciate some fresh insight.
This can happen if you have a Function or Sub that shares the same name as the Module. Every name must be unique. Even the Modules.

Wait for CSV file to open?

I am trying to download and open a CSV file using VBA in Excel. When I step through using the debugger my code works fine but when I try to run it normally it won't work, it is trying to copy the info from the newly opened CSV file into the existing .xlsm file but it isn't finding anything. I have found ways of checking that the file is open but I need it to keep checking and once it does exist to continue with the code.
Here is how Im getting the file to download:
Sub getFile(address)
On Error Resume Next
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate address
ie.Quit
Set ie = Nothing
On Error GoTo 0
End Sub
And then after this in the sub that calls getFile,
Do While Workbooks(Workbooks.Count).Name <> "file.csv"
Loop
Ive tried a few variations that all work fine when taking it slow in the debugger but crashes otherwise. Does anyone know a way to have it keep checking and wait until the file is open? It requires the user to do something so what it to make sure that file.csv is open. Should I put my check in sub getFile or keep it after it is called?
SOULTION:
Taking hnk's advice below I tried this and it worked perfectly:
Sub getFile(address)
On Error Resume Next
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate address
Do While Workbooks(Workbooks.Count).Name <> "file.csv"
DoEvents
Loop
ie.Quit
Set ie = Nothing
On Error GoTo 0
End Sub
Moved the check to before closing IE and added DoEvents to my loop.
Usually such behavior happens not because of the code logic but because of interrupts. Depending on the nature of your environment it could be one of two things
some background refreshing process is getting executed sometime in between your code execution time causing some issues. e.g. in a financial services environment, your Bloomberg API could be doing its timely BlpUpdate event
your code blocks up a large chunk of time and causes unexpected behavior because event which was triggered during your loop was blocked too long waiting for your code to complete on the main thread.
So you need to try the following two solutions, one of which should work
For the second problem, inside your
Do While Condition
' ... your code ...
Loop
add a line of code that checks for and clears any pending Event queues, making it...
Do While Condition
DoEvents ' either put it at the start or at the end of your code
' ... your existing code ...
Loop
This will give the system some 'breathing space' to wrap up pending events. You'll need to experiment with the location of your DoEvents code.
For the first problem, you can try enclosing your entire loop within an Event Protected area of code, to ensure it finishes running before anything disturbs it.
Application.EnableEvents = False
'your loop and other code comes here
Application.EnableEvents = True
Once again, you might need a bit of trial and error to see how much of the code needs to be thrown into the Event-free zone before it works as expected.

Resources