2017-08-14 63 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

感謝您的詳細解答! –

相關問題