2015-10-04 137 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 –