PDA

View Full Version : [SOLVED] Function in VBA (Excel) - Want a dynamic behavior depending on parameter



enggrahul78
04-14-2019, 08:12 PM
I am a newbie to excel VBA programming but I must admit its a very powerful tool. Irony it , I realized it after 20 years of using excel :crying:

Query - I am creating a function like below -

MVAR1,MVAR2,MVAR3 and MVAR4 are math variables. How I need to interpret these variables will be defined via. the string variable Whattodo.

If Whattodo = MVAR1 + MVAR2 + MVAR3 + MVAR4 ----- Function shall return the sum of all 4 variables.
If Whattodo = (MVAR1 + MVAR2 + MVAR3 + MVAR4)/4 ----- Function shall return the average all 4 variables.

There is no limit to the combinations of "Whattodo".............

How can i achieve this ????? Thanks in advance.

Function Correctanswer(MVAR1 As Long, MVAR2 As Long, MVAR3 As Long, MVAR4 As Long, Whattodo As String) As Long




Correctanswer = DO whatver is stored in Whatotdo


End Function

大灰狼1976
04-14-2019, 10:39 PM
Hi enggrahul78!
Welcome to vbax forum.
Please refer to the attachment.

Function Correctanswer(MVAR1 As Long, MVAR2 As Long, MVAR3 As Long, MVAR4 As Long, Whattodo As String) As Long
Dim s$
s = Whattodo
s = Replace(s, "MVAR1", MVAR1)
s = Replace(s, "MVAR2", MVAR2)
s = Replace(s, "MVAR3", MVAR3)
s = Replace(s, "MVAR4", MVAR4)
Correctanswer = Evaluate(s)
End Function


--Okami

enggrahul78
04-15-2019, 07:55 PM
Hi enggrahul78!
Welcome to vbax forum.
Please refer to the attachment.

Function Correctanswer(MVAR1 As Long, MVAR2 As Long, MVAR3 As Long, MVAR4 As Long, Whattodo As String) As Long
Dim s$
s = Whattodo
s = Replace(s, "MVAR1", MVAR1)
s = Replace(s, "MVAR2", MVAR2)
s = Replace(s, "MVAR3", MVAR3)
s = Replace(s, "MVAR4", MVAR4)
Correctanswer = Evaluate(s)
End Function


--Okami

大灰狼1976
04-15-2019, 08:06 PM
Hi enggrahul78!
Please mark the thread as [Solved] , thank you.
:beerchug: