Jump to content

VBA Datatype Declaration of Function

Hip

Hey guys

 

I'd like to know if it is necessary to declare the datatype of the output in the first line of the code after

 function Name () As Datatype

Since I tried out a small code and it worked, was it only coincidence?

 

And Also I'd like to know if it is also mandatory to fill the () ?

I worked on the following code where it all worked out without those two things.

 

Function datatypeTest() 
	dim firstValue As Double
    dim secondValue As Double
	dim output As Long
    
    firstValue = 1.2
    secondValue = 2.4
    output = firstValue + secondValue
    
    datatypeTest = output
End Function

 

Link to comment
Share on other sites

Link to post
Share on other sites

It work because it was valid syntax.

 

13 minutes ago, Hip said:

And Also I'd like to know if it is also mandatory to fill the () ?

Only if your function requires data being passed to it.

 

Microsoft docs

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/function-statement

https://docs.microsoft.com/en-us/office/vba/language/concepts/getting-started/understanding-named-arguments-and-optional-arguments

Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, C2dan88 said:

So when I use input from an Excel worksheet I'd have to fill in the variables into the () correct?

 

 

 

And in the first question the Function itself just grabs the datatype from the output varible's datatype right?

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, Hip said:

So when I use input from an Excel worksheet I'd have to fill in the variables into the () correct?

 

 

 

And in the first question the Function itself just grabs the datatype from the output varible's datatype right?

 

 

The actual way that VBA determines the return value of a function that doesn't explicitly declare it is somewhat ambiguous in their documentation. In general, you should always declare a function's return type in its signature (and you can force yourself to do this by setting "Option Explicit" at the top of the VBA doc.

 

There are different ways you could get Excel worksheet data into this function, but in my opinion yes you should probably create function arguments (the variables within the ()s ) and pass any data that your function will use into those.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×