尝试在单元格中查找确切string的下一个实例

我需要帮助find一个单元格中的确切string的下一个实例。

准确地说,我想查看一系列标题,find一个声明variables的下一个实例来获得列号,我想通过这一系列标题来查找下一个空单元格并保存该号码,最后,我想采取第一列号码,并从第二行search,直到我find一个空单元格的第一个实例,并将该数字保存到一个variables。 我一直在做的是这样的:

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

但似乎如果我不小心键入“S”,它会发现一个单元格的第一个实例包含一个string包含子string“(”姓氏),而不是第一个单元格只包含“S”。

我的恐惧是,如果在其中有“”的列,那么我的程序将无法正常工作。

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

我试着做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. 

如果将lookat参数设置为xlWhole,则只会匹配单元格的全部内容,例如:

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

要检查一个值是否被find,你可以检查是否找不到。

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

要find一行或一列值的第一个空单元格,我将使用End属性来查找包含数据的行/列中的最后一个单元格,然后使用偏移量查找下一个单元格:

 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中有更多的值)。

你可以使用一个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" 

代替消息框,把你想要做的任何代码与你find的。 第一个MsgBox将执行,如果find头(当x等于行号,y是列号)。 如果找不到所需的标题,则会执行第二个MsgBox。