循环遍历列时Excel宏“类型不匹配”错误

时间:2012-09-25 14:15:34

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

此函数的每次调用都会导致运行时错误“13”类型不匹配。为什么会这样?

Public Function VersionExists(versionId As String)

   VersionExists = False

   For Each cell In Tabelle2.Columns(1)
      If cell.Value = versionId Then
         VersionExists = True
      End If
   Next

End Function

2 个答案:

答案 0 :(得分:5)

您无法从cell.value访问.Columns(1),因为它会返回包含整个列的范围,而是

For Each cell In Sheet1.Columns(1).Rows '//or .cells

在比赛结束后也可以退出for循环。

答案 1 :(得分:2)

这是我在评论

中建议的替代方案
Public Function VersionExists(versionId As String) As Boolean
    Dim aCell As Range, rng As Range

    Set rng = Tabelle2.Columns(1)

    Set aCell = rng.Find(What:=versionId, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then VersionExists = True
End Function