为什么我会遇到"类型不匹配"错误?

时间:2018-05-06 13:33:42

标签: excel vba excel-vba variant type-mismatch

我正在尝试编写一个VBA函数,该函数将带有两列的表作为输入。我想返回第2列中第1列中相应行为3的元素。基本上相当于SQL中的where子句。

代码的逻辑似乎很好,但是我遇到了类型不匹配错误。我声明了函数As Variant,我想要返回的数组也是As Variant

Function FilterTable(tableName As String) As Variant
    Dim table As range
    Dim cell  As range
    Dim names As range
    Dim i     As Integer
    Dim names_2(100) As Variant
    Dim j As Integer
    Dim test As String

    i = 1
    j = 1
    Set table = ActiveSheet.range(tableName).Columns(1)
    Set names = ActiveSheet.range(tableName).Columns(2)

    For Each cell In table.Cells
        If cell = 3 Then
            names_2(i) = names.Cells(j, 1).Value
            i = i + 1
        End If
        j = j + 1
    Next

    FilterTable = names_2
End Function

为什么会出现类型不匹配错误,我该如何解决?

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题,但除非您的数据中存在工作表错误(例如#N / A,#DIV / 0!等),否则不会导致类型不匹配。

你应该知道你的桌子上有什么工作表;不要依赖活动表。

1-D阵列默认为从零开始,而不是从1开始。

填充后应删除数组中的多余(空)元素。使用“局部”窗口或在阵列上设置“监视”,以便在使用F8单步执行该功能时填充和调整大小。

Option Explicit

Sub main()
    Dim n As Variant, i As Long
    n = FilterTable("table1")
    For i = LBound(n) To UBound(n)
        Debug.Print n(i)
    Next i
End Sub

Function FilterTable(tableName As String) As Variant
    Dim table As Range, names As Range, cell As Range
    Dim i As Long, j As Long
    Dim names_2 As Variant

    i = 0
    j = 1
    ReDim names_2(100)
    Set table = Worksheets("Sheet3").Range(tableName).Columns(1)
    Set names = Worksheets("Sheet3").Range(tableName).Columns(2)

    For Each cell In table.Cells
        If Not IsError(cell) Then
            If cell = 3 Then
                names_2(i) = names.Cells(j, 1).Value
                i = i + 1
            End If
        End If
        j = j + 1
    Next cell

    ReDim Preserve names_2(i - 1)

    FilterTable = names_2
End Function