如何在列中查找文本并将行号保存在首次找到的位置 - Excel VBA

Kri*_*ina 12 excel vba

我有以下列(列A)命名为project(rows列只显示行号):

rows    project
1       14
2       15
3       16
4       17
5       18
6       19
7       ProjTemp
8       ProjTemp
9       ProjTemp
Run Code Online (Sandbox Code Playgroud)

我有一个输入消息框,用户在最后一个之后写入我想要插入的新项目名称.例如:项目20将在项目19之后和第一个"ProjTemp"之前插入.

我的理论是找到第一个"ProjTemp"的行号,然后在项目为20的位置插入一个新行.

我试图使用Find函数,但是我遇到了溢出错误(我确定我得到了它,因为它找到了3个"ProjTemp"字符串并尝试将其设置为一个参数):

Dim FindRow as Range

with WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        MatchCase:=False)
end with
Run Code Online (Sandbox Code Playgroud)

我如何编码,所以我只找到第一个"ProjTemp"的行号?有没有更好的方法来做到这一点,也许是循环?

谢谢,任何帮助将不胜感激!

man*_*ngo 22

我并不熟悉该Find方法的所有参数; 但在缩短它时,以下内容对我有用:

With WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With
Run Code Online (Sandbox Code Playgroud)

如果您只需要行号,可以在以下后使用:

Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row
Run Code Online (Sandbox Code Playgroud)


use*_*261 7

Dim FindRow as Range

Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
                   After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
                                                  ' column i.e. the first
                   LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
                   LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
                   SearchOrder:=xlByRows, _ 'This look down the column row by row 
                                            'Larger Ranges with multiple columns can be set to 
                                            ' look column by column then down 
                   MatchCase:=False) ' this says that the search is not case sensitive

If Not FindRow  Is Nothing Then ' if findrow is something (Prevents Errors)
    FirstRow = FindRow.Row      ' set FirstRow to the first time a match is found
End If
Run Code Online (Sandbox Code Playgroud)

如果你想获得额外的,你可以使用:

Do Until FindRow Is Nothing
    Set FindRow = Range("A:A").FindNext(after:=FindRow)
    If FindRow.row = FirstRow Then
        Exit Do
    Else ' Do what you'd like with the additional rows here.

    End If
Loop
Run Code Online (Sandbox Code Playgroud)