2017-01-05 99 views

回答

2

在这里你走,但请尽量找对谷歌第一

Sub eachCell() 
    Dim c As Range 
    For Each c In Range("A1:D21") 
     If (c.Value = "mytext") Then 'if value of cell = "specific text" 
      c.Value = "other text" 'do this 
      Else 
      c.Value = "other text 2" 'do that 
     End If 
    Next c 
End Sub 
+0

什么是'c.value =含义“等text'? – user007

+0

它对应于‘做’,在你的代码。它会改变细胞的价值”其他文字“ – nightcrawler23

0

使用查找循环会比看着每个单元

Sub Sample_Find() 
    Dim rng1 As Range 
    Dim rng2 As Range 
    Dim bCell As Range 
    Dim ws As Worksheet 
    Dim SearchString As String 
    Dim FoundAt As String 


    Set ws = Worksheets(1) 
    Set rng1 = ws.Columns(1) 

    SearchString = "specific text" 

    Set rng2 = rng1.Find(SearchString, , xlValues, xlWhole) 

    If Not rng2 Is Nothing Then 
     Set bCell = rng2 
     FoundAt = rng2.Address 
     MsgBox "do something here " & FoundAt 
     Do 
      Set rng2 = rng1.FindNext(After:=rng2) 

      If Not rng2 Is Nothing Then 
       If rng2.Address = bCell.Address Then Exit Do 
       FoundAt = FoundAt & ", " & rng2.Address 
       MsgBox "do something here " & rng2.Address 
      Else 
       Exit Do 
      End If 
     Loop 
    Else 
     MsgBox SearchString & " not Found" 
     Exit Sub 
    End If 

    MsgBox "The Search String has been found these locations: " & FoundAt 
    Exit Sub 


End Sub 
+0

为什么不去'AutoFilter',那会更快,没有? –

+0

什么是自动筛选器? 我该如何在这里使用它? – user007

+0

@ShaiRado取决于多少匹配 - 是的,如果很多 – brettdj

0

另一种选择更快地回答您的文章,使用AutoFilter

代码

Option Explicit 

Sub Test_AutoFilter() 

Dim ws As Worksheet 
Dim SearchString As String 
Dim Rng As Range 
Dim VisRng As Range 
Dim c As Range 

Set ws = Worksheets(1) 
Set Rng = ws.Columns(1) 

SearchString = "specific text" 

Rng.AutoFilter 
Rng.AutoFilter Field:=1, Criteria1:=SearchString 

' set another range to only visible cells after the Filter was applied 
Set VisRng = ws.Range(Cells(1, 1), Cells(1, 1).End(xlDown)).SpecialCells(xlCellTypeVisible) 

If Not VisRng Is Nothing Then 

    ' Option 1: show every cell that a SearchString was found 
    For Each c In VisRng 
     MsgBox "String match of " & SearchString & " found as cell " & c.Address 
    Next c 

    ' Option 2: show all the cells that SearchString was found (in 1 message) 
    MsgBox "String match of " & SearchString & " found as cells " & VisRng.Address 
End If 

End Sub 
+0

需要特殊单元的错误处理(在没有匹配的情况下) – brettdj

+1

我得到一个错误:'autofilter method of ra nge class failed' – user007

相关问题