VBA自定义函数来比较值

时间:2016-03-29 15:51:00

标签: vba excel-vba excel

我正在尝试创建一个基本上这样做的自定义函数:

  • 该功能位于F列,并查看C列以查看其中的值。
  • 如果是USA_USD,则会在colomn F
  • 中显示USD
  • 如果是Australia_AUD,它将在colomn F
  • 中显示AUD
Function The_Decider(DealCurrency, X)       
    If DealCurrency = "USA_USD" Then X = "USD"
    Else
    If DealCurrency = "Australia_AUD" Then X = "AUD"
    Else
    If DealCurrency = "Switzerland_CHF" Then X = "CHF"
    Else
    If DealCurrency = "China_CNY" Then X = "CNY"
    Else
    If DealCurrency = "EMU_EUR" Then X = "EUR"
    Else
    If DealCurrency = "Great Britain_GBP" Then X = "GBP"
    Else
    If DealCurrency = "Hong Kong_HKD" Then X = "HKD"
    Else
    If DealCurrency = "Japan_JPY" Then X = "JPY"
    Else
    If DealCurrency = "Korea(South)_KRW" Then X = "KRW"
    Else
    If DealCurrency = "Viet Nam_VND" Then X = "VND"
End Function

为什么我在C栏中获得#value

1 个答案:

答案 0 :(得分:5)

首先,您实际上并未提供任何返回值。另外,为了便于阅读,你可能会更好地选择Select Case块。

您应该在函数头中声明返回类型,然后使用与函数相同的名称来返回代码中的值:

Function The_Decider(ByVal DealCurrency As String) As String '// <~~ return type

    Dim X As String

    Select Case DealCurrency
        Case "USA_USD":             X = "USD"
        Case "Australia_AUD":       X = "AUD"
        Case "Switzerland_CHF":     X = "CHF"
        Case "China_CNY":           X = "CNY"
        Case "EMU_EUR":             X = "EUR"
        Case "Great Britain_GBP":   X = "GBP"
        Case "Hong Kong_HKD":       X = "HKD"
        Case "Japan_JPY":           X = "JPY"
        Case "Korea(South)_KRW":    X = "KRW"
        Case "Viet Nam_VND":        X = "VND"
        Case Else:                  X = "Unknown"
    End Select

    The_Decider = X '// <~~ the part that actually returns the value

End Function

虽然看到你的输入似乎有最后3个字母的货币代码,但我甚至不会使用UDF。只需使用工作表公式即可:

=RIGHT(C1,3)