Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

create simple function in VBA which calculate square root from given number

  1. User

    create simple function in VBA which calculate square root from given number

  2. Assistant

    Sure! Below is a simple VBA function that calculates the square root of a given number. You can insert this function into your VBA environment in Excel or any other application that supports VBA.

    Function CalculateSquareRoot(ByVal number As Double) As Double
        ' Check if the number is negative
        If number < 0 Then
            CalculateSquareRoot = CVErr(xlErrNum) ' Return an error for negative numbers
        Else
            CalculateSquareRoot = Sqr(number) ' Calculate square root for non-negative numbers
        End If
    End Function
    

    How to Use This Function:

    1. Open Excel (or another application that supports VBA).
    2. Press ALT + F11 to open the VBA editor.
    3. In the VBA editor, go to Insert > Module to create a new module.
    4. Copy and paste the above code into the module window.
    5. Close the VBA editor.

    Calling the Function:

    Now you can use CalculateSquareRoot function in a cell in Excel like this:

    =CalculateSquareRoot(A1)
    

    Where A1 contains the number you want to find the square root of. If you input a negative number, the function will return a #NUM! error. If the number is non-negative, it will return the square root.