使用Do Until在Excel VBA中查找特定文本

时间:2014-06-16 15:58:14

标签: excel vba excel-vba find excel-formula

我需要输入一个公式来从特定单元格中提取部分文本。这需要重复未知次数。我正在使用find函数的do语句。不幸的是,它只会连续发现第一次出现和循环。有没有办法强制找到下一个值? 任何人都可以帮助我吗?

以下是我正在使用的代码:

    Do

    With Columns("B")
        .Find(What:="total", After:=.Cells(1, 1), LookIn:=xlValues).Activate
    End With

     ActiveCell.Offset(0, -1).Select
     ActiveCell.FormulaR1C1 = "=LEFT(RC[1],12)"
     ActiveCell.Offset(1, 0).Activate
     ActiveCell.FormulaR1C1 = "=LEFT(RC[1],12)"



    Loop Until ActiveCell.Offset(0, 1) = "Grand Total"


    End Sub

Thank you for your assistance.
jfabro

I have been able to make the macro work to loop through the entire workseet however it does not stop when the condition is met. I believe the problem lies in the condition. What I am needing to say is to stop if the cell to the right of the active cell contains Grand Total.

Here is the new code I am using:
Do Until ActiveCell.Offset(0, 1) = "*Grand Total*"

With Columns("B")
    Cells.Find(What:="total", After:=ActiveCell, LookIn:=xlValues, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=False).Activate
End With

 ActiveCell.Offset(0, -1).Select
 ActiveCell.FormulaR1C1 = "=LEFT(RC[1],12)"
 Cells.FindNext(After:=ActiveCell).Activate

If ActiveCell.Offset(0, 1) = "*Grand Total*" Then


Exit Do

End If

Loop





End Sub

1 个答案:

答案 0 :(得分:0)

我觉得你的字符串匹配有问题,我会替换:

If ActiveCell.Offset(0, 1) = "*Grand Total*" Then


Exit Do

End If

使用:

If Instr(1,ActiveCell.Offset(0,1).value,"Grand Total")<>0 then Exit Do