简体   繁体   English

为什么会出现“类型不匹配”错误?

[英]Why do I experience a “Type Mismatch” error?

I am trying to write a VBA function that takes a table with two columns as input. 我正在尝试编写一个VBA函数,该函数将具有两列的表作为输入。 I want to return the elements in column 2 for which the corresponding row in column 1 is 3. Basically the equivalent of a where clause in SQL. 我想返回第1列中对应行为3的第2列中的元素,基本上等同于SQL中的where子句。

The logic of the code seems fine, however I get a type mismatch error. 代码的逻辑看起来不错,但是出现类型不匹配错误。 I declare the function As Variant and the array I want to return is As Variant as well. 我将函数声明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

Why do I get a Type Mismatch error, and how can I fix it? 为什么会出现类型不匹配错误,该如何解决?

There are a few problems with your code but nothing that should cause a type mismatch unless you have worksheet errors (eg #N/A, #DIV/0!, etc) in your data. 您的代码有一些问题,但是除非您的数据中存在工作表错误(例如,#N / A,#DIV / 0!等),否则不会导致类型不匹配的问题。

You should be aware of what worksheet your table is on; 您应该知道表所在的工作表。 don't rely on activesheet. 不要依靠activesheet。

A 1-D array defaults as zero-based, not one-based. 一维数组默认为从零开始,而不是从一开始。

You should remove the excess (empty) elements in your array after populating it. 填充数组后,应删除数组中多余(空)的元素。 Use the Locals window or set a Watch on your array to see it populate and resize as you step through the function with F8. 使用“本地”窗口或在数组上设置“监视”,以查看在使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM