在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 :(得分:1)
TRy-
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