arrays - VBA如何检查数组是否包含范围内的字符串

标签 arrays excel vba loops

我正在尝试编写一个小循环来检查所选范围是否包含数组中的任何值。

Sub test()
    Dim DirArray As Variant
    Dim i As Integer

    'define array
    DirArray = Sheets("Blad1").Range("A1:A311").Value

    'Loop trough array
    For i = 1 To UBound(DirArray)
        'Activate the sheet with the Range
        Sheets("Blad1").Activate

        'Go through range of values
        If DirArray = Cells(i, 2) Then
            MsgBox "it contains the value"
        End If
    Next i
End Sub

我认为我使用 Cells(i,2) 会出错,它说类型不匹配。我已经看了很长时间了,我想我错过了一些明显的东西。

任何帮助或反馈将不胜感激!

最佳答案

Sub test()
    Dim i As Integer, z, DirArray As Variant
    With Sheets("Blad1")
        'Define array
        DirArray = .Range("A1:A311").Value
        'Loop trough array
        For i = 1 To UBound(DirArray)
            '// Use Excel's Match function:
            '// if the value of 'z' is not Error, then match is found.
            '// Note that if you use WorksheetFunction.Match instead of
            '// Application.Match and the value won't be found, then
            '// error will be raised, in which case you need to use error handler.
            '// To avoid this ceremony, use Application.Match since it won't raise
            '// error, but the value of 'z' will just contain Error.
            z = Application.Match(.Cells(i, 2), DirArray, 0)
            If Not IsError(z) Then
                MsgBox "it contains the value"
            End If
        Next i
    Next
End Sub

关于arrays - VBA如何检查数组是否包含范围内的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59668775/

相关文章:

php - 引用 - 这个错误在 PHP 中意味着什么?

Java 十六进制到十进制的错误转换

VBA 'set typelib = createobject("scriptlet.typelib")'权限被拒绝

VBA 列表框拖放

php - 需要 PHP 代码来从数据库中选择大于 5 但不大于 15 的数字(意味着所有大于 5 的数字,不包括 15)?

c++ - 为什么这个指向指针二维数组的指针会像这样赋值new int

vba - 将数据从一个工作簿复制到另一个工作簿时出现超出范围错误

excel - 使用精确匹配和近似匹配来替代 vlookup 不起作用

php - 如何使用 Tiny But Strong 的 Excel 插件合并多个 Excel 文档?

sql - 在 MS Access 查询中使用多值字段