查找连续具有特定值的第一个和最后一个条目

时间:2017-06-08 12:25:58

标签: vba excel-vba excel

我有一个excel表,其中包含第一行中带有字符串foo的多个单元格。我想找到写入字符串的第一列和最后一列。我试过以下

Dim first_col As Integer
Dim last_col As Integer
Dim col As Integer
Dim found As Range
Dim ws_MLB as Worksheet
Dim foo as String

set ws_MLB = ThisWorkbook.Sheet(1)

Set found = ws_MLB.Rows(1).Find(foo)
If Not found Is Nothing Then
    col = found.Column
    first_col = col
    last_col = col
    Do
        found = ws_MLB.Rows(1).FindNext(found)
        col = found.Column

        If col < first_col Then
            first_col = col
            MsgBox ("This should not happen")
        ElseIf col > last_col Then
            last_col = col
        End If
    Loop While Not found Is Nothing And col <> first_col
Else
    MsgBox ("not found")
End If

但是这样我只得到first_col和last_col的第一个值。当我使用集成的Excel搜索搜索字符串时,我找到了多个实例。所以字符串就在那里。我做错了还是有更好的方法来做到这一点?

编辑忘记提及我也试图改变搜索方向,但我仍然得到了第一个条目。

2 个答案:

答案 0 :(得分:1)

您可以使用SearchDirection中的.Find参数,通过使用xlNext从左到右搜索然后xlPrevious从右到左搜索来使Sub FindFL() Dim wbk As Workbook Dim ws As Worksheet Dim fColumn As Long, lColumn As Long Set wbk = ThisWorkbook 'Change this to your workbook Set ws = wbk.Worksheets("Sheet1") 'Change this to your worksheet With ws 'Find first column that foo shows up fColumn = .Cells.Find(What:="foo", _ After:=.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlNext, _ MatchCase:=False).Column 'Find last column that foo shows up lColumn = .Cells.Find(What:="foo", _ After:=.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column Debug.Print "First Column is " & fColumn; vbNewLine _ ; "Last Column is " & lColumn End With End Sub 参数变得更容易。

{{1}}

答案 1 :(得分:-1)

我会这样做:

Public Sub foo()
  Dim nCol As Integer
  Dim nFirst As Integer
  Dim nLast As Integer

  With ActiveSheet
    nCol = 1
    Do Until .Cells(1, nCol) = ""
      If .Cells(1, nCol) = "foo" Then
        If nFirst = 0 Then
          nFirst = nCol
        Else
          nLast = nCol
        End If
      End If
      nCol = nCol + 1
    Loop
  End With

  MsgBox "First: " & nFirst & vbCr & "Last: " & nLast
End Sub