简体   繁体   English

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

[英]How to search specific column within range in VBA

Hello and thank you for taking the time to read this and thank you for any advice! 您好,感谢您抽出宝贵的时间阅读本文,并感谢您的任何建议!

I'm using VBA to search for the first value within an array which is greater than a value specified elsewhere in a cell, and outputting the column and row number to new cells. 我正在使用VBA搜索数组中的第一个值,该值大于单元格中其他位置指定的值,并将列和行号输出到新单元格。

The code I am using is: 我使用的代码是:

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

And that works fine. 而且效果很好。 However I now need to only search a certain column and just output the row value. 但是,我现在只需要搜索特定的列并仅输出行值即可。 The column I need to search is also specified in a specific cell. 我需要搜索的列也在特定的单元格中指定。 I've modified the code to: 我已将代码修改为:

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

This time I'm getting an error message type mismatch on the line "If cell.value > V Then" Can anybody spot why? 这次,我在“如果cell.value> V然后”这一行上收到一条错误消息类型不匹配的消息,有人可以找到原因吗?

Thanks 谢谢

The '.Cells' property needs to be specified for the range object in the second example: 在第二个示例中,需要为范围对象指定'.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM