2016-06-13 128 views
1

在Excel工作表中,我搜索关键字来标记列的标题,这是简单的部分。现在我需要在此列中搜索另一个字符串。重点是相同的字符串也出现在其他列中,但在不同的行上,所以这些需要被忽略。我发现这样做的唯一方法,就是通过这里介绍的方法:https://msdn.microsoft.com/en-us/library/office/ff839746.aspxExcel:搜索特定列中的文本

当我试图找到这样的字符串:

Dim moduleCol As Excel.Range = moduleSheet.Cells.Find("Module Naam") 
Dim upstreamRow As Integer 
With moduleSheet.Range(moduleCol, moduleSheet.Cells(moduleSheet.UsedRange.Row, moduleCol.Column)) 
    upstreamRow = .Find(upstreamEm).Row 
End With 

找到字符串,但在错误的列(和因此在错误的行)。在我的例子表,我知道我在列“d”进行搜索,所以对于测试的目的,我想:

Dim upstreamRow As Integer 
    Dim testCol As Integer 
    With moduleSheet.Range("d1:d500") 
     Dim testCell As Excel.Range = .Find(upstreamEm) 
     upstreamRow = testCell.Row 
     testCol = testCell.Column 
    End With 

现在字符串也完全看不到,即使它是目前在此列(在细胞d14)。我错过了什么?有没有更好的方法来找到它?

回答

1

像这样的东西应该做的伎俩。它会找到第一个值,然后将第二个值的查找范围设置为仅查找找到第一个值的列。显然,它需要进行调整以满足您的需求,但它应该能够帮助您。下面的代码是我的数据集的截图:

Sub test() 

Dim fVal As String 
Dim fRange As Range 

fVal = "TEST2" 

Set fRange = ActiveSheet.Cells.Find(What:=fVal, LookIn:=xlFormulas, LookAt _ 
     :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ 
     False, SearchFormat:=False) 

If Not fRange Is Nothing Then 

    fVal = "B" 

    Set fRange = ActiveSheet.Columns(Split(fRange.Address, "$")(1)).Find(What:=fVal, LookIn:=xlFormulas, LookAt _ 
     :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ 
     False, SearchFormat:=False) 

    fRange.Select 

End If 

End Sub 

enter image description here

+0

谢谢!起初它不起作用,因为不知何故我正在寻找的值是formule的结果(使用连接字符串等),现在我将其更改为一个值,现在它可以工作。你能解释一下ActiveSheet.Columns(Split(fRange.Address,“$”)(1))的功能吗? – DrDonut

+1

那件东西拉着一个单元格引用的Column Letter,它在'Columns()'函数中使用 –

+0

啊,因为地址被格式化为'$ D $ 1',这是有道理的!谢谢! – DrDonut