2017-08-14 93 views
-1

我是新来的stackoverflow,并已发现它非常有用。希望有人会在下面回答我的问题。运行时错误'13'类型不匹配:如果或者

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

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

我尝试过以下几行的排列,但它们不能解决问题。

Dim Currency1 As String 

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

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

+1

您不能对字符串值进行“或”操作,即“USD”或“CNY”不是合理的计算。你想'如果货​​币=“美元”或货币=“人民币”或...然后'。 – YowE3K

+0

@ YowE3K您的评论是有用的,谢谢。对不起,尽管在决定发布问题之前,我已经完成了其他帖子。 (编辑:以及你删除了评论,但我会道歉。) –

回答

0

为什么不简单呢? 声明一个字符串变量来保存所有货币并使用Instr函数检查Currency1变量是否有效。

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 
+0

感谢它的工作。 –

+0

@JTg不客气!很高兴它的工作。 :) – sktneer

0
If Currency1 = "USD" Or Currency1 = "CNY" Or Currency1 = "GBP" Or Currency1 = "AUD" Or Currency1 = "NZD" Then 
+0

感谢它的工作。 –

0

除了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 
+0

感谢您的详细解答! –