如何在VBA中搜索范围内的特定列

时间:2018-10-03 13:46:55

标签: excel vba

您好,感谢您抽出宝贵的时间阅读本文,并感谢您提供任何建议!

我正在使用VBA搜索数组中的第一个值,该值大于单元格中其他位置指定的值,并将列号和行号输出到新的单元格中。

我使用的代码是:

Sub A()

Dim rng As Range
Dim v As Variant
Dim colnum As Long
Dim row As Long

Set rng = Range("B2:BT72")
v = Sheets("WIP").Range("AC76").Value
For Each cll In rng
If cll.Value > v Then
    colnum = cll.Column
    row = cll.row
Exit For
End If
Next
Sheets("WIP").Range("AF76").Value = colnum + 25
Sheets("WIP").Range("AG76").Value = row + 25

End Sub

那很好。但是,我现在只需要搜索特定的列并仅输出行值即可。我需要搜索的列也在特定的单元格中指定。我已将代码修改为:

Sub B()

Dim rng As Range
Dim v As Variant
Dim x As Variant
Dim row As Long

Set rng = Range("A2:BT72")
v = Sheets("WIP").Range("AC77").Value
x = Sheets("WIP").Range("AF77").Value

For Each cell In rng.Columns(x - 25)
If cell.Value > v Then
    row = cell.row
Exit For
End If
Next
Sheets("WIP").Range("AG77").Value = row + 25

End Sub

这次,我在“ If cell.value> V Then”行中收到错误消息类型不匹配的信息 有人可以找到原因吗?

谢谢

1 个答案:

答案 0 :(得分:0)

在第二个示例中,需要为范围对象指定'.Cells'属性:

Sub B()

    Dim rng As Range
    Dim v As Variant
    Dim x As Variant
    Dim row As Long

    Set rng = Range("A2:BT72")
    v = Sheets("WIP").Range("AC77").Value
    x = Sheets("WIP").Range("AF77").Value

    For Each cell In rng.Columns(x - 25).Cells
        If cell.Value > v Then
            row = cell.row
            Exit For
        End If
    Next
    Sheets("WIP").Range("AG77").Value = row + 25

End Sub