【问题标题】:Search a table based on the value of more than one cell per row根据每行多个单元格的值搜索表
【发布时间】:2017-10-17 14:48:56
【问题描述】:

我正在尝试查找输入到表格中的单位的先前值(该单位的数据是整行)。随着时间的推移,单位中的一列中的值会增长,我正在尝试使用循环根据每行中的两个值分析每一行,并在为该特定单位输入新值时返回该特定单位中的前一个值单元。

'My Variables

    Dim current_size As Integer
    Dim last_size As String
    Dim joint_number As Integer

    Dim tool_sizes As Range: Set tool_sizes = drill_log.Range("Drill_Log[Tool Size]")
    Dim joints As Range: Set joints = drill_log.Range("Drill_Log[Joint '#]")
    Dim pass_types As Range: Set pass_types = drill_log.Range("Drill_Log[Pass Type]")
    Dim row As Range

    'Finds the current pass size and last pass size and assigns it to the current pass size variables
        If pass_type = ream Then
            current_size = drill_log.Range("W" & last_ream_range.row)
            joint_number = drill_log.Range("C" & last_ream_range.row)

        ElseIf pass_type = intersect_ream Then
            current_size = drill_log.Range("W" & last_intersect_ream_range.row)
            joint_number = drill_log.Range("C" & last_intersect_ream_range.row)
        Else
            Exit Sub
        End If

    'Finds the previous pass size for the last joint entered

        For Each row In drill_log.Range("Drill_Log")

'Line that Errors
          If pass_types.Value = pass_type And joints.Value = joint_number Then
          If tool_sizes < current_size Then
                    last_size = tool_sizes
                Else
                    last_size = "NONE"
                End If
            Else
            End If

        Next row

我的目标是让它检查每一行中的指定列,如果匹配,则如果包含信息的列中的单元格小于当前单元格,则将其分配给变量。

现在它告诉我我有一个类型不匹配,我无法解决它。 感谢您的帮助。

【问题讨论】:

  • 哪一行错误?
  • 对不起“如果 pass_types.Value = pass_type And Joints.Value = joint_number Then”行。倒数第 9 个
  • 您似乎没有定义(或声明)pass_type。它们都是单细胞范围吗?
  • 除此之外还有大约 200 行代码。未定义的变量在别处分配。 pass_type 是一个字符串。
  • 我假设我的变量中声明的范围被程序自动假定为引用它当前所在的行。对吗?

标签: vba excel for-loop range


【解决方案1】:

Range.Value 与字符串或数字或任何内容进行比较的指令出现类型不匹配错误,几乎可以肯定是由于Range.Value 包含错误值。

修复数据并确保这些单元格中永远不会出错:

=IFERROR([whatever formula you have here], "")

或者更改代码,使其不再假定单元格中不能有错误:

If Not IsError(pass_types.Value) And Not IsError(joints.Value) Then
    If pass_types.Value = pass_type And joints.Value = joint_number Then
        '...
    End If
End If

...或者安全起见,尽可能两者兼而有之。


类型不匹配的原因是当IsError(Range.Value)True,那么Range.Value的类型是Variant/Error,而VBA不知道如何比较一个@ 987654329@ 对任何事物都有价值。

复制:

Debug.Print TypeName(CVErr(xlErrNA))       'prints "Error"
Debug.Print IsError(CVErr(xlErrNA))        'prints "True"
Debug.Print CVErr(xlErrNA)) = vbNullString 'type mismatch
Debug.Print CVErr(xlErrNA)) = 0            'type mismatch

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2015-01-17
    相关资源
    最近更新 更多