thedanotto
thedanotto

Reputation: 7327

excel VBA return result of function

Simple Layup for anyone. I've written a function isMac() which looks at the current operating System, if the first 3 letters are Mac, it is supposed to return True. I then want to assign the return value of the function to a variable in another function. I'm currently running a Mac, so when I run the following code, the MsgBox says True, while the Debug.Print returns False

Function isMac() As Boolean
  If Left(Application.OperatingSystem, 3) = "Mac" Then
    result = True
  Else
    result = False
  End If
  MsgBox result
End Function

Sub test()
  Debug.Print isMac()
End Sub

How do I correctly return a Boolean from my IF statement so that I can utilize it in another function?

Upvotes: 1

Views: 270

Answers (1)

user4039065
user4039065

Reputation:

Try assigning the result to the function.

Function isMac() As Boolean
  isMac = CBool(LCase(Left(Application.OperatingSystem, 3)) = "mac")
End Function

Sub test()
  Debug.Print isMac()
End Sub

Another approach would be Compiler Directives and Compiler Constants. In a module code sheet's declarations area as,

#If Mac Then 
    Public Const bMAC as Boolean = True
#Else 
    Public Const bMAC as Boolean = False
#End If

Use bMAC anywhere in your code to determine whether the OS is a Mac or not.

Upvotes: 2

Related Questions