“用户定义的类型未定义”错误,没有突出显示行 - 错误是什么?

时间:2017-03-22 14:52:39

标签: excel vba excel-vba

我对VBA很新。我正在尝试编写一个函数,它将返回包含值的列数。

因此,例如,如果“A”列在A列中为2x,在B列中为3x,在ColumnC中为0x,则该函数将返回2.

当我运行它时,它会给我一个错误 - “未定义用户定义的类型”。 VBA并未指出存在问题的特定行。

Function countUniqueCols(toFind As Text, CASarray As Object) As Integer
    Dim numCols As Integer
    numCols = 0
    Dim currentCol As Column
    For Each currentCol In CASarray.Columns
        For Each currentRow In currentCol.Rows
            If InStr(1, Cells(currentRow, currentCol).value, toFind) Then
                numCols = numCols + 1
                Exit For
            End If
        Next currentRow
    Next currentCol
    countUniqueCols = numCols
End Function

思考?非常感谢!

2 个答案:

答案 0 :(得分:2)

卫生署!!!我在这一点上摸不着头脑,甚至试图单步执行代码 - 然后我突然发现它 - 文字

<div class='background'> </div>

应该是:

Function countUniqueCols(toFind As Text, CASarray As Object) As Integer

Function countUniqueCols(toFind As String, CASarray As Range) As Integer 不是有效的VBA数据类型。

然后,当我认为我解决了问题时,我尝试再次运行它,并找到Text,这需要Column,即

Range

应该是

Dim currentCol As Column

然后我发现Dim currentCol As Range 没有被定义。并且currentRow错了。

以下代码应该有效:

Cells(currentRow, currentCol)

但是Shai的代码会更好,所以我只是把它留在这里,这样你就可以看到现有代码中存在的细微错误。

答案 1 :(得分:1)

由于无关紧要(根据您的帖子)在列中找到toFind的次数(只要它的&gt; = 1),您就可以遍历CASarray范围列,每列使用Application.Match查找单个匹配。

在这种情况下,如果If Not IsError(Application.Match(toFind, currentCol, 0)) Then表示在此列中找到匹配项,那么将计数添加到numCols

我添加的第二个Sub是为了确保在调用此函数时使用正确的参数(并且完全合格)。

功能countUniqueCols 代码

Option Explicit

Function countUniqueCols(toFind As String, CASarray As Range) As Long

    Dim numCols As Long, currentCol As Range

    numCols = 0

    For Each currentCol In CASarray.Columns
        If Not IsError(Application.Match(toFind, currentCol, 0)) Then
            numCols = numCols + 1
        End If
    Next currentCol
    countUniqueCols = numCols

End Function

Sub Test_countUniqueCols 代码(测试功能)

Sub Test_countUniqueCols()

Dim Res As Long

Res = countUniqueCols("Shai", Worksheets("Sheet1").Range("A1:D1000"))    
MsgBox Res

End Sub