2015-06-26 26 views
1

我負責從工作簿中的每月工作表中提取兩個特定行數據。VBA工作表數據提取以搜索多個值

使用MyVal和搜索框的當前代碼僅與一個搜索兼容。如何更改代碼&搜索框功能與多個搜索兼容?

當前的代碼如下所示:

Sub Set_Hyper() 
    ' Object variables 
    Dim wks As Excel.Worksheet 
    Dim rCell As Excel.Range 
    Dim fFirst As String 
    ' {i} will act as our counter 
    Dim i As Long 
    ' Use an input box to type in the search criteria 
    Dim MyVal As String 
    MyVal = InputBox("What are you searching for", "Search-Box", "") 
    ' if we don't have anything entered, then exit the procedure 
    If MyVal = "" Then Exit Sub 
    Application.ScreenUpdating = False 
    Application.DisplayAlerts = False 

    '  Add a heading to the sheet with the specified search value 
    With Cells(1, 1) 
     .Value = "Found " & MyVal & " in the Link below:" 
     .EntireColumn.AutoFit 
     .HorizontalAlignment = xlCenter 
    End With 
    i = 2 
    '  Begin looping: 
    '  We are checking all the Worksheets in the Workbook 
    For Each wks In ActiveWorkbook.Worksheets 
     If wks.Name <> "Data" Then 

     '  We are checking all cells, we don't need the SpecialCells method 
     '  the Find method is fast enough 
      With wks.Range("A:A") 
      '   Using the find method is faster: 
      '   Here we are checking column "A" that only have {myVal} explicitly 

       Set rCell = .Find(MyVal, , , xlWhole, xlByColumns, xlNext, False) 
      '   If something is found, then we keep going 
       If Not rCell Is Nothing Then 
       '    Store the first address 
        fFirst = rCell.Address 
        Do 
        '     Link to each cell with an occurence of {MyVal} 
         rCell.Hyperlinks.Add Cells(i, 1), "", "'" & wks.Name & "'!" & rCell.Address 
         wks.Range("B" & rCell.Row & ":R" & rCell.Row).Copy Destination:=Cells(i, 2) 

         Set rCell = .FindNext(rCell) 
         i = i + 1 'Increment our counter 
        Loop While Not rCell Is Nothing And rCell.Address <> fFirst 
       End If 
      End With 
     End If 
    Next wks 
    ' Explicitly clear memory 
    Set rCell = Nothing 
    ' If no matches were found, let the user know 
    If i = 2 Then 
     MsgBox "The value {" & MyVal & "} was not found on any sheet", 64, "No Matches" 
     Cells(1, 1).Value = "" 
    End If 
    ' Reset application settings 
    Application.ScreenUpdating = True 
    Application.DisplayAlerts = True 
    End Sub 

回答

0

我想你可以做的是創建一個用戶窗體與下面的控件:

一個文本框 一個ListBox 一個按鈕添加文本到列表框 運行VBA的另一個按鈕

文本框可以包含搜索字符串。您可以通過點擊按鈕來完成以下活動:

1)將文本從文本框添加到列表框中。查找AddItem方法來執行此操作。 2)清除文本框的內容,這樣就可以添加新的值。

添加完成後,您可以在代碼中添加另一個for循環,以添加到列表框中的每個項目。這樣,您可以根據添加的內容進行多次搜索。

希望這有助於:)