代码之家  ›  专栏  ›  技术社区  ›  J Tg

运行时错误“13”类型不匹配:If或[重复]

  •  -1
  • J Tg  · 技术社区  · 7 年前

    Currency1 = Application.WorksheetFunction.HLookup("Currency", _ 
    Worksheets("abc").Range("T5:Z6"), 2, False)
    ...
    Currency1 = "USD" Or "CNY" Or "GBP" Or "AUD" Or "NZD" Then
    

    弹出类型不匹配错误。
    在添加“或…”语句之前,它可以正常工作。

    Dim Currency1 As String
    
    If Currency1 = ("USD" Or "CNY" Or "GBP" Or "AUD" Or "NZD") Then
    

    任何帮助都将不胜感激,谢谢。

    3 回复  |  直到 7 年前
        1
  •  0
  •   Subodh Tiwari sktneer    7 年前

    为什么不这么简单?

    Dim Currency1 As String
    Dim strCurr As String
    strCurr = "USD,CNY,GBP,AUD,NZD"
    Currency1 = "GBP"
    If InStr(strCurr, Currency1) > 0 Then
        'Do your stuff here if the Currencey1 is a valid currency
    End If
    
        2
  •  0
  •   Diveye    7 年前
    If Currency1 = "USD" Or Currency1 = "CNY" Or Currency1 = "GBP" Or Currency1 = "AUD" Or Currency1 = "NZD" Then
    
        3
  •  0
  •   Vityata    7 年前

    还有另一种选择,除了 If Currency1 = "USD" Or Currency1 = "CNY" 意见中已经提出。它有点复杂,它使用了一个额外的函数,检查值是否在数组中。

    因此,在这种情况下,我们可以将数组作为字符串传递 "USD:AUD:DEM" 或作为实数数组 Array("USD", "AUD", "DEM") ,这取决于我们的需要。在下面的例子中,我展示了两种选择。

    Option Explicit
    
    Public Function b_value_in_array(my_value As Variant, my_array As Variant, Optional b_is_string As Boolean = False) As Boolean
    
        Dim l_counter
    
        If b_is_string Then
            my_array = Split(my_array, ":")
        End If
    
        For l_counter = LBound(my_array) To UBound(my_array)
            my_array(l_counter) = CStr(my_array(l_counter))
        Next l_counter
    
        b_value_in_array = Not IsError(Application.Match(CStr(my_value), my_array, 0))
    
    End Function
    
    Public Sub TestMe()
    
        Dim Currency1 As String
    
        Currency1 = "USD"
    
        If b_value_in_array(Currency1, Array("USD", "AUD", "DEM")) Then
            Debug.Print "Value is in the array."
        End If
    
        If b_value_in_array(Currency1, "USD:AUD:DEM", True) Then
            Debug.Print "Value is in the array."
        End If
    
    End Sub