【问题标题】:VBA < Operator causes Type Mismatch ErrorVBA < 运算符导致类型不匹配错误
【发布时间】:2015-01-27 11:02:00
【问题描述】:

我正在使用以下代码根据两个标准隔离某些数据集,(1) 关键字(即用户 1); (2) 标称值

以下代码似乎适用于 Microsoft Excel 2013,但在 Microsoft Excel 2010 上向我抛出了不匹配错误。如果您能提供帮助,那就太好了。

代码如下:

  Sub FinalApprover()
     lastRow = Sheets("Source").Cells(Rows.Count, 1).End(xlUp).Row

     For i = 2 To lastRow
        If Sheets("Source").Cells(i, 1).Value = "User 1" And ("Source").Cells(i, 2) < 50000 Then

          Sheets("Source").Cells(i, 3).Value = "Final Approver"
       End If
     Next

 End Sub

【问题讨论】:

  • 错误是否发生在If Sheets("Source").cells(i, 1).value .... 行上,您确定是&lt; 运算符引发了错误吗? 2 列中的单元格是否格式化为数字? i 的哪个值,因此哪个单元格会导致错误?
  • 你试过在.Cells(i, 2) 后面加上.value 吗?
  • 嗨,伙计们,对不起,这不是 .value,因为我实际上有它,只是在我在这里重新编写时忘记这样做了

标签: vba excel


【解决方案1】:

错误在您正在测试的工作表中的值范围内。 您很可能需要使用某种形式的数据验证来确保第 1 列中有字符串值,第 2 列中有数字值。

我相信一些错误处理可能会对这种情况有所帮助。 运行此函数代替旧函数,如果再次引发错误,此函数将写入错误所在的行以及您与硬编码 String "User 1" & Integer 50000 然后暂停执行。程序停止后,您将能够通过按“CTRL + G”在“立即”窗口中看到这些值。

Sub FinalApprover_New()
    Dim r As Long, lLastRow As Long
    Dim wsSource As Worksheet
    Dim bDebug As Boolean

    Set wsSource = ThisWorkbook.Sheets("Source")

    With wsSource
        'lLastRow = wsSource.Cells(Rows.Count, 1).End(xlUp).Row
        lLastRow = .Rows.Count
        For r = 2 To lLastRow
            ' bDebug is used to attempt to compare the values ahead of time to check if an exception is thrown.
            bDebug = (.Cells(r, 1).Value = "User 1" And .Cells(r, 2) < 50000)
            If Err.Number <> 0 Then
                Debug.Print "Row: " & r & " | " & "Value 1: " & .Cells(r, 1).Value & " | Value 2: " & .Cells(r, 2).Value
                Debug.Assert 0 ' Hardcoded breakpoint
            End If
            If .Cells(r, 1).Value = "User 1" And .Cells(r, 2) < 50000 Then
                .Cells(r, 3).Value = "Final Approver NEW"
                Exit For
            End If
        Next
    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多