试图在单元格中查找精确字符串的下一个实例

时间:2014-06-11 17:53:29

标签: excel excel-vba methods syntax vba

我需要帮助在单元格中查找精确字符串的下一个实例。

准确地说,我想查看一系列标题并找到声明变量的下一个实例以获取列号,我想查看该系列标题以查找下一个空单元格并保存数字,最后,我想取第一列,并从第二行搜索,直到找到空单元格的第一个实例,并将该数字保存到变量中。我一直在做的是:

With Rows(1)
    Set found = .Find(what:=Target, After:=.Cells(1, 1))
End With

但似乎如果我不小心输入“s”,它将找到包含字符串的第一个实例,该字符串包含子串“s”(LastName),而不是第一个仅包含“s”的单元格。

我担心如果列中包含“”,那么我的程序将无法正常运行。

除此之外,我按列排序,当该列中的单元格为空时,程序将其一直推到列表底部,我试图删除该空单元格空间。

我尝试过做Application.WorksheetFunction.Match,HLookup和VLookup,一般来说工作表函数对我不起作用。

所以只是举一个我想做的例子:

I have 10 Columns with headings. I want to find the first instance of a column that 
contains exactly the string I send into this class. For instance, if the
columns are "FirstName | LastName | Name", I want it to return "Name" 
and not "FirstName". 

I want to find a column that the user requests as a sort key and verify it's existence
I also want to find a column that is empty (last column)
Finally, I want to find the last row that has a value in relation to the SortColumn.

2 个答案:

答案 0 :(得分:1)

如果将the lookat parameter设置为xlWhole,它将仅匹配单元格的全部内容,例如:

With Rows(1)
    Set found = .Find(what:=target, After:=.Cells(1, 1), lookat:=xlWhole)
End With

要检查是否找到了值,您可以检查找不到任何值。

Dim exists As Boolean
If Not found Is Nothing Then exists = True

要在值的行或列的末尾找到第一个空单元格,我将使用End property查找包含数据的行/列中的最后一个单元格,然后使用Offset查找下一个单元格:

With Rows(1)
    Set found = .Find(what:=target, After:=.Cells(1, 1), lookat:=xlWhole)
End With
Dim emptyCell As Range

If Not found Is Nothing Then
    Dim col As Integer
    col = found.Column
    Set emptyCell = Columns(col).End(xlDown)
    emptyCell.Offset(1, 0).Select
End If

但是,如果值表中间有一些空单元格,则无法使用此单词。 (例如,如果您有A1,A2,A3中的值,则A4为空白,您在A5,A6,A7中有更多值)。

答案 1 :(得分:0)

您可以使用do循环:

headerToFind = "Name" 'or whatever header you're looking for
x = 1 'or whatever header row is
y = 1 'or whatever first column with header is
Do Until Cells(x,y) = ""
    If Cells(x,y) = headerToFind then
        MsgBox "The header you are looking for is in row " & x & ", column " & y
        Exit Sub
    End If
    y = y + 1
Loop
MsgBox "Header not found"

代替消息框,将您想要的任何代码放在您找到的内容中。如果找到标题,则第一个MsgBox将执行(x等于行号,y是列号)。如果找不到所需的标题,则会执行第二个MsgBox。