Question:
How to refer to a value in a separate function in visual basic?
Stawt
2011-04-28 05:03:26 UTC
In microsoft visual basic (using excel), i have a subprogram which, along with a bunch of other things, calculates the area of something. I have also written a function which has a formula in it, but the function relies on the area calculated in my sub to work but i don't know how to let the function refer to that area, it just says the variable is undefined. I do not want to set it as a global variable, i think i need to use ByVal but i dont really have any idea what that means.
Three answers:
stratsandlespauls
2011-04-28 09:50:43 UTC
You might want to change the sub to a function that returns a value

then you take this value and pass it to the next function.

This is psuedo code

dim myArea as decimal=0

myArea=CalculateArea



private function CalculatedArea() as decimal

'do your math

return myCalculation

end function

'now pass this to the next function

'that is passing byVal

MyOtherFunction(myArea)
?
2011-04-28 17:51:15 UTC
Sounds like you need to include parameters into your function (can also be used in a SUB). These are values which are passed to the Sub or Function when you Call it (use it).



You add parameters when you decalre the function (write it) by adding variables and their datatypes winthin the parenthesis.



So if you have a function like:

Private Function getArea() as double



You need to modifiy it to add the parameters like so:

Private Function getArea(ByVal Length as double, ByVal Width as Double) as Double

in your code within this function you can use the two variables Length and Width in your formula







Now in your other subroutine you can pass the data by supplying either numbers or variables inside the parenthesis when you call that function





Dim answer as double

Dim L as double



L = 10



answer = getArea(L, 20)





This passes the values 10 for length and 20 for width to the getArea Function
?
2011-04-28 12:05:02 UTC
Neither do I dude


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...