2017-10-06 39 views
1

在Excel中使用VBA查看單元格是否包含存儲在我的數組中的值,但該值不起作用。我收到類型不匹配錯誤。需要查看數組中是否存在某個單元格的值

Sub ExecuteScript_Click() 
    Dim vals As String 
    vals = Array("5", "9", "12") 

    Dim LastRow As Long 
    Dim i As Long 
    LastRow = Range("A" & Rows.Count).End(xlUp).Row 
    For i = 2 To LastRow 
     If Range("A" & i).Value = vals Then 
     Range("B" & i).Value = "Value Exists" 
     End If 
    Next i 
End Sub 
+0

您正在嘗試一個**單值**比較的** **陣列。你需要一個內部循環或一個'Filter()'。 –

+0

您正在比較單元值與孔陣列 - 這會引發錯誤。循環遍歷數組中的所有條目,編寫一個函數來執行檢查(也可以循環)或使用「Dictionary」而不是數組 – FunThomas

+1

您也不能將一個簡單變量聲明爲一個String,然後將一個數組到它。 'vals'應該是一個變體,然後你可以循環它。 – Rory

回答

1

試戴

Sub foo() 
Dim vals As Variant 

vals = Array("5", "9", "12", "-1") 
Dim LastRow As Integer 

Dim i As Long 
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 



For i = 2 To LastRow 
     If IsInArray(ActiveSheet.Range("A" & i).Value, vals) Then 
     ActiveSheet.Range("B" & i).Value = "Value Exists" 


    End If 
Next i 

End Sub 


Function IsInArray(key As Variant, arr As Variant) As Boolean 
    IsInArray = (UBound(Filter(arr, key)) > -1) 
End Function 

參考。 HERE

修訂

Sub foo() 
Dim vals As Variant 

vals = Array("5", "9", "12", "-1") 
Dim LastRow As Integer 

Dim i As Long 
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 



For i = 2 To LastRow 
    If Not IsEmpty(ActiveSheet.Range("A" & i)) Then 
     If IsInArray(ActiveSheet.Range("A" & i).Value, vals) Then 
      ActiveSheet.Range("B" & i).Value = "Value Exists" 
     End If 
    End If 
Next i 

End Sub 


Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean 
    IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) 
End Function 
+0

感謝您提供此信息。我不熟悉VBA或VB,需要跳轉。我想我會在這個週末看一些101個視頻,但我現在被卡住了 - 謝謝! – Sean

+0

上面的代碼也會將空值標記爲現有值;你可以通過定義一個條件來避免這一點,例如'如果Len(ActiveSheet.Range(「A」&i).Value)> 0那麼在將「Value Exists」寫入列B中的單元格之前。 –

+0

@ T.M。謝謝指出 –

相關問題