需要查看数组中是否存在单元格的值

时间:2017-10-06 11:30:16

标签: vba excel-vba excel

在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

1 个答案:

答案 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