• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Error in VBA code Odd Even Function.

Nitesh Khot

Member
Hi.,..Unable to get solution for how to check no is odd or even using below code...

Code:
Function checkoddeven(x As Range) As Boolean
chekoddeven = ""

If Iseven(x) = True Then

checkoddeven = "Even No"

ElseIf IsOdd(x) = True Then

checkoddeven = "Odd No"

Else

checkoddeven = "Check No Correct"

End If


End Function
 
Hi !​
Code:
Function EvenOdd(L As Long) As String
         EvenOdd = IIf(L Mod 2, "Odd No", "Even No")
End Function
Do you like it ? So thanks to click on bottom right Like !
 
Hi,

Firstly, the second line in your code has a typo: it's really important to use Option Explicit to pick mistakes like that up.

Secondly, your code is missing 2 functions: IsEven() and IsOdd(). The VBA object model does not have IsEven() and IsOdd() functions so you have to either implement them yourself or use the Excel's worksheet functions. I will put to one side which would be better.

Thirdly, your function has been defined to return a Boolean value (TRUE or FALSE) but the code itself tries to assign a String value to it. That will result in a #VALUE! error. I think all UDFs should be written to return Variant types so that they can return errors.

Assuming that (1)you want to return a string and (2) you meant to call Excel's worksheet functions, your code would be:

Code:
Function checkoddeven(x As Range) As Variant
checkoddeven = ""

If WorksheetFunction.IsEven(x) = True Then

checkoddeven = "Even No"

ElseIf WorksheetFunction.IsOdd(x) = True Then

checkoddeven = "Odd No"

Else

checkoddeven = "Check No Correct"

End If

End Function
 
Back
Top