issue with concatenated subs - vba

DISCLAIMER: I'm not a developer, just an average guy trying to use VBA on his own project. First time I post on stackoverflow so forgive me if I'm violating any unwritten community rule..
Hi all, I'm trying to have a bunch of subs running in sequence, so the next one starts only when the previous one has finished.
The problem is that excel keep on crashing during the execution, while if I run each sub manually they have no issue at all.
So far I have been using this method: First I have a mini sub that assigns value=1 to the global variable "oneclick", and then calls the first macro of the chain
then, in each sub there is a tiny piece just before the end:
sub macro1()
...macro code...
if oneclick=1 then
call macro2
end if
end sub
and so on for all the subs until the final sub resets the oneclick variable to zero.
I have no idea why this keeps on crashing. I can see that actually none of these subs is really closing until the very end of the last one, would this hit any sort of code limitation? I would be actually happier to have a single master sub that directs the process instead of relying on a kludge like this! any suggestion?
EDIT:
oh wow already so many answers.. now I'm gonna try some of those. Answering some of your questions:
1) the crash is really something sudden, not even an error message, simply excel quits and reopens, in the same state as it was when the macro chain first started.
2) I agree with you guys that there should be a master sub calling the smaller ones, however last time I tried I got a series of problems because one macro needs to work on the results of the previous one and so on. How do you tell to vba to wait until the previous sub has ended?

It is best if you don't chain the macros, but instead call them from another sub. This way you will have a clear way of understanding what you are doing, in what order.
Sub AllOfIt()
macro1
DoEvents
macro2
DoEvents
macro3
End Sub
Sub macro1
...
End Sub
Sub macro2
...
End Sub
Sub macro3
...
End Sub
There is generally no need to worry about if something starts before the previous macro ended. That does not happen unless you do something like using Application.OnTime

What probably is happening is that oneclick is not defined with a Dim statement, so by default its defined at procedure level, meaning if you set oneclick it to 0 in another Sub, your setting another local/procedure level variable, and your variable in macro1 is unchanged, so your chain of macros never stops, which leads to a stack overflow/crash as stated in one of the comments above.
So either define oneclick as public variable (I recommend to define it as Boolean as it seems to basically be a switch .... True/False) or you pass the variable as argument down your chain of macros ( Sub Macro2(ByRef oneclick as Boolean) ).
All that said, as one of comments above stated, you can have all your chained subs in the main sub ( macro1 ) as they will only get executed one after the other, e.g.
Sub macro1()
Dim oneclick As Boolean
oneclick = True 'Need to get set to true to start
If oneclick Then Call macro2(oneclick)
If oneclick Then Call macro3(oneclick)
........
End Sub
Sub macro2(ByRef oneclick As Boolean)
oneclick = False 'One of your macros has to set oneclick to false to stop the chain/execution, probably under acondition
End Sub

Related

Cannot run the macro

I have encountered a problem in the macro below
Sub RefreshAction()
Range("b7").Select
Application.Run "RefreshCurrentSelection"
Application.OnTime (Now() + TimeValue("00:00:05")), "thisworkbook.Action"
End Sub
The cell refreshes when I run the macro the first time but I get the error message immediately after
Message: Cannot run the macro "C\Desktop\XYZ.xlsm'!thisworkbook.Action'. The macro may not be available in this workbook or all macros may be disabled.
I have already gone through "Trust Center->Trust Center Settings->Macro Settings->Enable all macros and it didn't work.
The "Trust access to VBA project object model" box is also clicked.
First of all, here is a snapshot of the error you get when you attempt to run OnTime from a worksheet (not a module) as I will explain. I was getting this error too and trying to figure out why.
It looks like a security error, but in this case it isn't exactly a normal security error.
To run code on a timer you have to add it to a VBA module.
Go to the VisualBasic editor and right click the VBAProject (book).
In Excel it looks like the following:
Once the module is added you add your timer code there.
Since you want to call RefreshAction every 5 seconds you would do something like the following:
Sub StartProcess()
Debug.Print Now()
Application.OnTime Now() + TimeValue("00:00:05"), "RefreshAction", Schedule = True
End Sub
Sub RefreshAction()
Application.EnableEvents = True
Debug.Print Now() + TimeValue("00:00:05")
Application.OnTime Now() + TimeValue("00:00:05"), "RefreshAction", Schedule = True
End Sub
I'll let you add the code that you want it to do each time in the RefreshAction subroutine.
Here's what it will look like in the Module. Make sure yours shows that it is in a module as it does in the image:
Also, I found it to be quite flaky. If you have anything even slightly wrong in the OnTime call it will fail silently. Copy my code (I tested it) and try it first. Once it runs, just add your code to the RefreshAction sub.
StartProcess()
Run the StartProcess to start the thing going.
Additionally Odd Thing
After I added that Module, I still had my code in the Worksheet and I went back and attempted to run it to see the error again and the odd thing is that once the code is in the Module you won't get the error from the Worksheet any more. It's probably referencing the code in the Module now.
See the absolute reference for more details : CPearson OnTime
First issue, you need to store the time that you'll input in your OnTime method to be able to stop it. (Here I declared a Public TimeToRun As Date)
Second Point To use the OnTime method continuously, you need to reset the timer at the end of your timed procedure (here RefreshAllStaticData).
So your whole code should look like this :
Public TimeToRun As Date 'so that TimeToRun can be used in both the functions
Sub RefreshAction()
Range("b7").Select
Application.Run "RefreshCurrentSelection"
DoEvents
'Store the next date of execution in TimeToRun
TimeToRun = Now() + TimeValue("00:00:05")
'Launch the next OnTime
Application.OnTime TimeToRun, "RefreshAllStaticData"
End Sub
Sub RefreshAllStaticData()
'--++-- Place your code here, as it is now --++--
'----Call RefreshAction to reset the OnTime method
'---------to another 5 seconds and keep "looping"
RefreshAction
End Sub
Sub Kill_OnTime()
'Launch this to stop the OnTime method
Application.OnTime _
earliesttime:=TimeToRun, _
procedure:="RefreshAllStaticData", _
schedule:=False
End Sub
A different but related cause of this error can be the string-length limitation of the OnTime method's Procedure parameter's argument. See my post at: Getting around the Max String size in a vba function?

Application.ontime code isn't running

I've done a fair bit of research on here to try and get this code to run, but I'm still having issues.
I am trying to run a macro at a set time. In fact it is a number of macros as different times. This macro then copies a block of cells, into a different area on the sheet.
I will not be able to use windows scheduler so I'm trying to do it this way. I gather without scheduler I will have to run the macro from a button. Therefore, my first sub is this (note button is on a separate sheet to the data)
Sub Call_save()
Call Sheets("Dashboard").8amsave
Application.OnTime TimeValue("08:10:00"), "Call_8amsave"
Call 9amsave
Application.OnTime TimeValue("09:10:00"), "Call_9amsave"
Call 10amsave
Application.OnTime TimeValue("10:10:00"), "Call_10amsave"
End Sub
This button is designed to then run the subs at the predetermined time. The subs it calls are these:
Sub 8amsave()
Dim current_data As Variant
current_data = Worksheets("Dashboard").Range("S6:V22").Value
Worksheets("Dashboard").Range("B33:E49").Value = current_data
End Sub
Sub 9amsave()
Dim current_data As Variant
current_data = Worksheets("Dashboard").Range("S6:V22").Value
Worksheets("Dashboard").Range("B54:E70").Value = current_data
End Sub
Sub 10amsave()
Dim current_data As Variant
current_data = Worksheets("Dashboard").Range("S6:V22").Value
Worksheets("Dashboard").Range("B75:E91").Value = current_data
End Sub
Now, when I run the initial button it runs all the subs at once and copies the sells into the correct places, straight away. This isnt really an issue for me. However, at the predetermined time I get an error saying unable to run the macro... can't find it or sheet unable to run macros... or something of that ilk.
Is there anything blindingly obvious that i am missing? I have kind of been working this out as I go along so my VBA knowledge is fairly limited. A point in the right direction would be great.
Your OnTime statements also appear to be referencing procedure names which don't exist, i.e., Call_8amSave as opposed to 8amsave. Note also that procedure names cannot begin with numeric (e.g., 8amsave) and this code should not even compile, let alone execute.
Rename your procedures so that they match the calls in the OnTime statement, and are legally permissible procedure names, like: Sub Call_8amSave, etc.
Also, the OnTime property can only have one procedure at a time, so you can't set 3 future times, you have to set them sequentially. So, set the OnTime for the 9am save during the 8am procedure, etc.
Option Explicit
Sub Call_save()
Application.OnTime TimeValue("08:10:00"), "Call_8amsave"
End Sub
Sub Call_8amsave()
With Worksheets("Dashboard")
.Range("B33:E49").Value = .Range("S6:V22").Value
End With
Application.OnTime TimeValue("09:10:00"), "Call_9amsave"
End Sub
Sub Call_9amsave()
With Worksheets("Dashboard")
.Range("B54:E70").Value = .Range("S6:V22").Value
End With
Application.OnTime TimeValue("10:10:00"), "Call_10amsave"
End Sub
Sub Call_10amsave()
With Worksheets("Dashboard")
.Range("B75:E91").Value = .Range("S6:V22").Value
End With
End Sub

Turning off a worksheet change-based event macro in Excel

I've been stuck on this for awhile. I have a macro that runs every time a change is made and creates a data table that updates after each change with information like : Old Value, New Value, Data Changes, etc.
I am trying to kind of pause the worksheet change macro when I don't want it to be run anymore. Ex: If I am plugging in blank information, I don't need to document the fact that it used to be blank, and now it has data, etc.
I made some specifications for if I deleted an entire row as shown here:
If Target.Address = Target.EntireRow.Address Then Exit Sub
but that only dealt with one case. I just now thought of a very simple solution that I will post as the answer, so I hope this will help other people as much as it helped me
It's actually a very simple solution.
To begin pick a cell that has no information in but can be clearly located. For the purpose of this lets say A1.
Now pick key words that you will use to turn the macro on and off. Ex: I just chose True and False (capitals need to be consistent so pick what you want)
At this point, go to the beginning of your worksheet change macro and type in this right after the sub starts:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1").Value = "False" Then
Exit Sub
End If
Now, before your macro starts, it will always verify that the cell doesn't contain False, so if you want it on, put anything else but False, and if you want it off, keep the cell as False. Hope this helps someone.
You want to disable events while ensuring that you enable them later. To do this, use an error handler to catch all errors and set the state back at the end.
Public Sub example()
On Error GoTo errHandler
Application.EnableEvents = False ' => disable events
'The code ...
errHandler:
Application.EnableEvents = True ' => enable events
End Sub

Application.Quit in UserForm attempts to run rest of macro before exiting

My question is: using VBA in Excel 2013 how can I gracefully close an entire instance of Excel when the user decides they don't want to fill out a UserForm and clicks quit or cancel?
Currently, if the user clicks quit or cancel, I check to see if my instance is the only one open. If it is not, I can use ThisWorkbook.Close and I think I will be okay. However, if it is, I do not want the application to still be present, so I used Application.Quit. This, though, tries to finish running the macro, throws errors (originally "type mismatch" because I unload the form), and only closes after I click "Debug" or "End" (which it does so fast for either I cannot actually debug). I'm ignoring the first case for now and just trying to exit the entire application. It's a very long macro with a lot of subroutines and functions, so for debugging and posting here, I have shortened it. The type mismatch error no longer occurs, but I believe that was a consequence of the actual error: code running after the command to close the application is called.
First, here's the code that starts everything:
Private Sub CommandButton1_Click()
Call form_variables
frm_REQUEST.Show
Call a_REQUEST_main
End Sub
The subroutine
form_variables
is a subroutine that creates public variables so I can store the data from the UserForm.
frm_REQUEST.Show
initializes (including calling a function that finds another workbook, extracts a list, does some formatting, closes the workbook and enters the list into the userforms drop down box) and shows the form, and finally
a_REQUEST_main
uses the public variables (where UserForm data is stored) and does its thing (but shouldn't do anything if the UserForm is closed).
The code that is executed when .Show is called is:
Private Sub UserForm_Initialize()
' Get job numbers from other workbook
Dim job_selection_list As Variant
job_selection_list = get_job_list()
With frm_REQUEST.Job_Number_ComboBox
.List = job_selection_list
End With
' set focus on Job Numbers
JN_combobox.SetFocus
End Sub
Private Sub cancel_button_Click()
Set job_selection_list = Nothing
Unload Me
Application.Quit
End Sub
Private Sub submit_button_Click()
' Values from userform saved as global (?) variables so other subroutines can access.
End Sub
I stepped through the program and saw that, once Application.Quit is called in the UserForm, the macro, in the main subroutine, steps to
Call a_REQUEST_main
but it should really just close everything out. I tried doing "save" commands, and changing the order of things, and read about objects needing to be set to nothing (hence the setting of the job_selection_list which is created when the drop down list is initialized), but I cannot seem to get this to work, or find anything online. Can anyone provide some guidance or let me know of a better way to close an excel instance? Help me Stack-Overflow Kenobi, you're my only hope!
Thanks.
Just add a variable to account for when the user closes the form
in the form
'hold flag if users cancels form
Public btnCancel As Boolean
Private Sub CommandButton1_Click()
Unload Me
btnCancel = True
End Sub
'set the flag each time the form active
Private Sub UserForm_Activate()
btnCancel = False
End Sub
then in your code
Call form_variables
frm_REQUEST.Show
If frm_REQUEST.btnCancel Then
Application.Quit
Else
Call a_REQUEST_main
End If
Put Application.Quit in the form's Terminate event handler instead of in the button's Click event handler.
The reason is that clearly the procedure will keep running even if the form has unloaded. So use the events to your advantage.
Putting it in the Click event will unload the form, but the procedure will keep running which of course may raise errors or other undesired effects.
Note: You may be prompted to save/discard changes (if any) to the workbook.

'28' Out of Stack Space. Worksheet_Change and Application.ScreenUpdating

thanks in advance for any clarity you can offer.
In an Excel Workbook with many modules and worksheets, at the bottom of the VBA code for SHEET2, there is this Subroutine:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim TargetCells As Range
Set TargetCells = Range("B1000:B1029")
If Not Application.Intersect(TargetCells, Range(Target.Address)) Is Nothing Then
Call SpecificSubRoutine
End If
End Sub
My understanding of this code is that it watches the entire sheet for ANY changes. If ANYTHING is changed, anywhere on the sheet, it runs the If statement. The If statement fails in the event that any of the changes made to the sheet take place outside of the specified TargetCells range, but this Sub still tries to validate the If statement EVERY time ANYTHING is changed on the sheet.
Now, you might be able to guess that my problem is some stack overflow. (Run-time error '28': Out of Stack Space)
Whenever the Worksheet_Change Sub runs, if the changes to the sheet were made inside of the TargetCells range, it calls SpecificSubRoutine which populates cells, which triggers the Worksheet_Change Sub for every time SpecificSubRoutine populates ANY cell. (SpecificSubRoutine also calls different modules, which of course populate cells, which of course trigger the Worksheet_Change Sub)
Not so good.
Also, most of the subroutines throughout the application are wrapped in Application.ScreenUpdating = False / Application.ScreenUpdating = True, which I mistakenly thought would limit the number of times Worksheet_Change is called to once, immediately after Application.ScreenUpdating = True runs.
NOTE OF IMPORTANCE: Neither SpecificSubRoutine nor any of the Subroutines called by it populate cells in the TargetCells range. I'm not quite that dim...
Here are my questions:
Is there a way to narrow the scope of what triggers the Worksheet_Change Sub, so that only changes in the TargetCells range triggers it? (instead of changes anywhere in the sheet)
Is there a way to do what I mistakenly thought that Application.ScreenUpdating would do? (make changes to the sheet all in one bulk update, as opposed to triggering a change with nearly every step)
Also, as an extra curiosity, is there a way to have Worksheet_Change watch 2 specific ranges (instead of the whole sheet?) Knowing how to do this would be paramount, and would likely solve all of the problems on this sheet.
My intuition is to add an End to the last part of SpecificSubRoutine, or to the end of any/all of the Subroutines called by it, but I'm just not sure this will circumvent the looping through Worksheet_Change multiple times, since Application.ScreenUpdating doesn't bulk update like I thought.
Ideas?
Part 1: No - the event handler responds to all changes on the sheet: any filtering in how you respond to that change must occur in the handler itself.
Part 2: answered by #simoco
Part 3 (and incorporating simoco's suggestion):
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents=False
If Not Application.Intersect(Me.Range("B1000:B1029"), Target) Is Nothing Then
Call SpecificSubRoutine
End If
If Not Application.Intersect(Me.Range("D1000:D1029"), Target) Is Nothing Then
Call SomeOtherSpecificSubRoutine
End If
Application.EnableEvents=True
End Sub