【问题标题】:Excel macro "type mismatch" error while looping through a column循环遍历列时出现 Excel 宏“类型不匹配”错误
【发布时间】:2012-09-25 22:32:30
【问题描述】:

每次调用此函数都会导致运行时错误“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

【问题讨论】:

  • 请使用Option Explicit!您必须显式声明所有变量,但这会大大减少此类错误的数量。

标签: vba excel type-mismatch mismatch


【解决方案1】:

您不能从.Columns(1) 访问cell.value,因为它会返回包含整个列的范围;

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

在比赛结束后退出 for 循环也是个好主意。

【讨论】:

  • + 1 我还建议使用.Find 而不是循环
【解决方案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

【讨论】:

    猜你喜欢
    • 2017-01-27
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多