I would like to call a sub from another sub inside in the same module. The first sub would be my main code and there I would call the second subroutine. Second subroutine receives multiple inputs as integer, double, double arrays and double matrices. The size of the arrays and matrices are known and stored in an integer variable. The sub also returns several outputs. So, I would like to do something like this.
sub Main() Nc As integer Dim kij(1 To Nc, 1 To Nc), xi(1 to Nc), a1 As Double 'I assign values to my variables from the excelsheet e.g. Nc=Cells(1,1) etc. CalculateA(Nc,kij, xi, a1, a) Cells(5,5)=a end sub sub CalculateA(Nc as integer,kij as matrix double, xi as array double, a as Double) a=0 For i=1 To Nc For j=1 To Nc a = a + kij(i,j)*x(i)*x(j) Next j Next i a = a*a1 end sub
How does it know which sub is the main sub where it starts to run. Can I put the secondary sub on top and the code somehow starts from the bottom subroutine?
What is Call Sub in VBA? We can execute all the sub-procedures of the same module in a single subroutine, and the process of executing them in a single VBA subroutine. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA. read more called “Call Sub.”
Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.
To call a sub inside another sub you only need to do:
Call Subname()
So where you have CalculateA(Nc,kij, xi, a1, a)
you need to have call CalculateA(Nc,kij, xi, a1, a)
As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...)
cause this way it does not appear in the macro list and it's easier to work
Hope it helps, Bruno
PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With