When programming in Excel VBA, I often switch off Calculation and ScreenUpdating (sometimes also DisplayAlerts, etc.), do some lengthy calculations, and switch them back to their previous states (not necessarily on because these functions may call each other). So I would like to have a standard way for this.
There are no lambda functions in VBA but Application.Run may be an acceptable solution, so I came to this code:
Public Function FastRun(strMacroQuoted As String, ParamArray varArgs() As Variant) As Variant Dim blnOldScreenUpdating As Boolean: blnOldScreenUpdating = Application.ScreenUpdating Application.ScreenUpdating = False Dim clcOldCalculation As XlCalculation: clcOldCalculation = Application.Calculation Application.Calculation = xlCalculationManual FastRun = Application.Run(strMacroQuoted, varArgs(0)) Application.Calculation = clcOldCalculation Application.ScreenUpdating = blnOldScreenUpdating End Function
I could give all parameters from varArgs to Run one by one (from 0 to 29), and so my FastRun would not constrain the number of parameters beyond the limit set by Run.
My question is: Is there any better (neater) solution than writing 30 parameters after each other?
It's not obvious why you're calling Application.Run
. I guess there are two possibilities: 1. that you're calling a procedure from another workbook or an add-in, or 2. that, for some reason, you need to call a procedure within your current project by its name, passed as a string.
Assuming you want to stick with the structure of passing all of your arguments via a ParamArray
into a routine which then calls Application.Run
, your 'run' procedure would need to have a Variant
as its argument instead of a ParamArray
. The ParamArray
is an array and the Variant
would interpret as such when passed. So your code would look something like this:
Public Sub Main1() CallingRoutine "MyRoutine", 1, 2, 3 End Sub Public Sub CallingRoutine(routineName As String, ParamArray varArgs() As Variant) Application.Run routineName, varArgs End Sub Public Sub MyRoutine(arr As Variant) Debug.Print "Item 0 ="; arr(0) Debug.Print "Item 1 ="; arr(1) Debug.Print "Item 1 ="; arr(2) End Sub
I suspect there might be better ways of achieving your task and if you could provide a little more detail we might be able to help you more. The main questions would be why do you need to call your routine by Application.Run
, where is your code located and what are the variables contained in your varArgs
array?