如何在列中查找文本并将行号保存到Excel VBA中
我有以下列(列A)命名项目(行列只是显示行号):
rows project 1 14 2 15 3 16 4 17 5 18 6 19 7 ProjTemp 8 ProjTemp 9 ProjTemp
我有一个input消息框,用户在那里写入新的项目名称,我想要插入最后一个。 例如:项目20将在项目19之后和第一个“ProjTemp”之前插入。
我的理论是find第一个“ProjTemp”的行号,然后插入一个新的行,其中的项目是20。
我试图使用查找function,但我得到一个溢出错误(我敢肯定,我得到它,因为它find3“ProjTemp”string,并试图将其设置为一个参数):
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
我如何编码,所以我只find拳头“ProjTemp”的行号? 有没有更好的方法来做到这一点,也许是一个循环?
谢谢,任何帮助将不胜感激!
我不太熟悉Find
方法的所有参数; 但缩短之后,下面是为我工作:
With WB.Sheets("ECM Overview") Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues) End With
如果你只需要行号,你可以使用这个:
Dim FindRowNumber As Long ..... FindRowNumber = FindRow.Row
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 ie 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
如果你想获得额外的,你可以使用:
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
或者,你可以使用循环,保持行号(计数器应该是行号),并find第一个“ProjTemp”时停止循环。
那么它应该看起来像这样:
Sub find() Dim i As Integer Dim firstTime As Integer Dim bNotFound As Boolean i = 1 bNotFound = True Do While bNotFound If Cells(i, 2).Value = "ProjTemp" Then firstTime = i bNotFound = false End If i = i + 1 Loop End Sub
几点意见:
- 由于search位置很重要,因此应指定开始search的位置。 我在下面使用
ws.[a1]
和xlNext
,所以我的search从指定表格的A2
开始。 -
Find
的一些参数 – 包括lookat
使用之前的search设置。 所以你应该总是指定xlWhole
或xlPart
分别匹配全部或部分string。 - 你可以做所有你想要的 – 包括插入一行,并提示用户一个新的价值(我的代码将build议20,如果先前值是19),而不使用
Select
或Activate
build议的代码
Sub FindEm() Dim Wb As Workbook Dim ws As Worksheet Dim rng1 As Range Set Wb = ThisWorkbook Set ws = Wb.Sheets("ECM Overview") Set rng1 = ws.Range("A:A").Find("ProjTemp", ws.[a1], xlValues, xlWhole, , xlNext) If Not rng1 Is Nothing Then rng1.EntireRow.Insert rng1.Offset(-1, 0).Value = Application.InputBox("Please enter data", "User Data Entry", rng1.Offset(-2, 0) + 1, , , , , 1) Else MsgBox "ProjTemp not found", vbCritical End If End Sub
检查“projtemp”,然后检查前一个是否是一个数字条目(如19,18 ..等),如果是这样,然后得到该项目的临时温度….
如果不是这样的话,那么重新检查一下前面的条目是projtemp还是一个数字条目…