2015-10-04 229 views
0

Excel - VBA 我想知道如何使用VBA查找Excel範圍的行。防爆。 「要找到的單詞」,這不僅僅是單元格的值,而是一個字符串的單詞。例如,查找字符串「網絡」到「需要幫助來映射網絡打印機」字符串的方法。查找單元格到單元格

Sub SearchForSfb() 

    Dim LSearchRow As Integer 
    Dim LCopyToRow As Integer 

    On Error GoTo Err_Execute 

    'Start search in row 1 
    LSearchRow = 1 

    'Start copying data to row 2 in Open (row counter variable) 
    LCopyToRow = 2 

    While Len(Range("E" & CStr(LSearchRow)).Value) > 0 

     'If value in column E = "word to be found", copy entire row to Open 
     If Range("E" & CStr(LSearchRow)).Value = "word to be found" Then 

     'Select row in Data to copy 
     Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select 
     Selection.Copy 

     'Paste row into SFB in next row 
     Sheets("SFB").Select 
     Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select 
     Sheets("SFB").Paste 

     'Move counter to next row 
     LCopyToRow = LCopyToRow + 1 

     'Go back to Data to continue searching 
     Sheets("Data").Select 

     End If 

     LSearchRow = LSearchRow + 1 

    Wend 

    'Position on cell A3 
    Application.CutCopyMode = False 
    Range("A3").Select 

    MsgBox "All matching data has been copied." 

    Exit Sub 

Err_Execute: 
    MsgBox "An error occurred." 

End Sub 
+1

參見[短語內計數的關鍵字(http://stackoverflow.com/questions/32860792/count-keywords-within-phrases/32878493#32878493) – Jeeped

回答

0

使用一個簡單的循環

Sub Button1_Click() 
    Dim ws As Worksheet 
    Dim sh As Worksheet 
    Dim lstRw As Long 
    Dim rng As Range 
    Dim s As String 
    Dim c As Range 

    s = "* network *" 

    Set ws = Sheets("Data") 
    Set sh = Sheets("SFB") 

    With ws 
     lstRw = .Cells(.Rows.Count, "E").End(xlUp).Row 
     Set rng = .Range("E2:E" & lstRw) 
    End With 

    For Each c In rng.Cells 
     If c.Value Like s Then 
      c.EntireRow.Copy sh.Cells(sh.Rows.Count, "A").End(xlUp).Offset(1) 
     End If 
    Next c 


End Sub 

或者你可以使用過濾器的宏

Sub FiltExample() 
    Dim ws As Worksheet, sh As Worksheet 
    Dim rws As Long, rng As Range 
    Set ws = Sheets("Data") 
    Set sh = Sheets("SFB") 

    Application.ScreenUpdating = 0 

    With ws 
     rws = .Cells(.Rows.Count, "E").End(xlUp).Row 
     .Range("E:E").AutoFilter Field:=1, Criteria1:="=*network*" 
     Set rng = .Range("A2:Z" & rws).SpecialCells(xlCellTypeVisible) 
     rng.EntireRow.Copy sh.Cells(sh.Rows.Count, "A").End(xlUp).Offset(1) 
     .AutoFilterMode = False 
    End With 

End Sub 
+0

非常感謝您的回覆,從您的代碼中我將使用「s」變量部分在我的VBA中使用它,它很好地工作。 ''查找s的單詞s =「* SFB *」 '如果列E =中的值被找到,則將整行復制到Open If Range(「E」&CStr(LSearchRow))。 'Thx –

相關問題