找出变量的范围,使一个简单的函数正常工作

时间:2015-01-23 04:25:52

标签: excel vba excel-vba excel-2010 excel-2007

以下VBA例程无效,我无法弄清楚为什么......

我尝试在顶部设置一组公共变量,使变量在函数之间进行,但它不起作用。

以下代码的最终结果应使getthename的值为cow

Sub test()
    getthename = test2(test1("elephant"))
End Sub

Function test1(NewTitle As String) As String
    If NewTitle = "elephant" Then
        NewTitle = "horse"
    Else
        NewTitle = "pig"
    End If
End Function

Function test2(NewTitle As String) As String
    If NewTitle <> "horse" Then
        NewTitle = "cow"
    Else
        NewTitle = "rabbit"
    End If
End Function

1 个答案:

答案 0 :(得分:2)

你应该让你的函数实际返回一个值:

Sub test()
    getthename = test2(test1("elephant"))
End Sub

Function test1(NewTitle As String) As String
    If NewTitle = "elephant" Then
        test1 = "horse"
    Else
        test1 = "pig"
    End If
End Function

Function test2(NewTitle As String) As String
    If NewTitle <> "horse" Then
        test2 = "cow"
    Else
        test2 = "rabbit"
    End If
End Function