2014-06-16 90 views
0

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

这里是我使用的代码:

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 
+0

它听起来像你可能应该改变'.Cells(1,1)'引用来使用每次运行循环时都会增加的索引变量。可能类似'.Cells(index,1)'(... stuff in loop ...)'index = index + 1' – chancea

+1

http://msdn.microsoft.com/en-us/library/office/ff839746 (v = office.15).aspx显示了如何在循环中使用Find。 –

+0

这帮助了Tim,但现在在弹出错误之前它会遍历整个文件2次。 – user3689031

回答

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