简体   繁体   中英

VBA excel function syntax

I need to write an excel macro, to read length of triangle sides and check if this triangle exists, also if it exists macro should define type of triangle, then output result. Here is my code -

Public Function tri(a, b, c)
    Public answer As String
    If a + b <= c Or b + c <= a Or c + a <= b Then
        answer = "triangle doesn't exist"
    ElseIf a = b = c Then
        answer = "eq triangle"
    ElseIf a = b Or c = a Or b = c Then
        answer = "isosceles triangle"
    ElseIf (a + b) ^ 2 = c ^ 2 Or (a + c) ^ 2 = b ^ 2 Or (c + b) ^ 2 = a ^ 2 Then
        answer = "right triangle"
    Else
        answer = "regular triangle"
    End If
    ActiveCell = answer
End Function

I'll appreciate any help.

We must:

  1. fix the Dim
  2. return the answer:



Public Function tri(a, b, c) As String
    Dim answer As String
    If a + b <= c Or b + c <= a Or c + a <= b Then
        answer = "triangle doesn't exist"
    ElseIf a = b = c Then
        answer = "eq triangle"
    ElseIf a = b Or c = a Or b = c Then
        answer = "isosceles triangle"
    ElseIf (a + b) ^ 2 = c ^ 2 Or (a + c) ^ 2 = b ^ 2 Or (c + b) ^ 2 = a ^ 2 Then
        answer = "right triangle"
    Else
        answer = "regular triangle"
    End If

    tri = answer
End Function

在此处输入图片说明

I think Select Case is a more appropriate syntax in such cases

moreover you can get rid of backing variable

Public Function tri(a, b, c) As String
    Select Case True
        Case a + b <= c Or b + c <= a Or c + a <= b
            tri = "triangle doesn't exist"
        Case a = b = c
            tri = "eq triangle"
        Case a = b Or c = a Or b = c
            tri = "isosceles triangle"
        Case (a + b) ^ 2 = c ^ 2 Or (a + c) ^ 2 = b ^ 2 Or (c + b) ^ 2 = a ^ 2
            tri = "right triangle"
        Case Else
            tri = "regular triangle"
    End Select
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM