在我的项目中,我现在使用的是Application.WorksheetFunction.Match
方法,也是一种方法,我可以遍历列中的所有值,使其与我选择的内容相匹配。我想知道哪一个在搜索中更快。我只有一张包含大约50个条目的表格(随着时间的推移会逐渐增长)所以我无法真正测试它,而且我不知道Application.WorksheetFunction.Match
是如何工作的。任何指导都会很棒。
谢谢
Application.WorksheetFunction.Match
方法
Private Sub Search1(comboBox, sheet, rangeFrom, message As String, columnNumber As Integer)
Dim range, rangeList As range, strSelect As String, lastRow, row As Long, wksNew As Excel.Worksheet
Dim value, value2 As Variant
Dim ws As Worksheet
Set wks1 = Worksheets(sheet)
If comboBox.ListIndex <> -1 Then
strSelect = comboBox.value
lastRow = wks1.range("A" & Rows.Count).End(xlUp).row
Set rangeList = wks1.range((rangeFrom) & lastRow)
On Error Resume Next
row = Application.WorksheetFunction.Match(strSelect, wks1.Columns(columnNumber), 0) ' searches the worksheet to find a match
On Error GoTo 0
If row Then
For Each ws In Sheets
Application.DisplayAlerts = False
If (ws.Name = "Search Results") Then ws.Delete
Next
Application.DisplayAlerts = True
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = "Search Results"
wks1.Rows(row).EntireRow.Copy 'copys the found row
emptyRow = WorksheetFunction.CountA(ws.range("A:A")) + 1 ' finds the next empty row
ws.Paste (ws.Cells(emptyRow, 1)) 'pastes the row in the empty row
Application.CutCopyMode = False 'closes the paste funtion to stop manual pasting
Else
MsgBox "No Results were Found. ", vbInformation, "No Results" ' displays a messgae box if nothing is found
Exit Sub
End If
End If
End Sub
迭代方法
Private Sub Search2(comboBox, sheet, rangeFrom, message As String, columnNumber As Integer)
Dim range, rangeList As range, strSelect As String, lastRow, row As Long, wksNew As Excel.Worksheet
Dim value, value2 As Variant
Dim ws As Worksheet
Dim i As Integer
Set wks1 = Worksheets(sheet)
i = 2
If comboBox.ListIndex <> -1 Then
strSelect = comboBox.value
lastRow = wks1.range("A" & Rows.Count).End(xlUp).row
Set rangeList = wks1.range((rangeFrom) & lastRow)
On Error Resume Next
row = Application.WorksheetFunction.Match(strSelect, wks1.Columns(columnNumber), 0) ' searches the worksheet to find a match
On Error GoTo 0
If row Then
For Each ws In Sheets
Application.DisplayAlerts = False
If (ws.Name = "Search Results") Then ws.Delete
Next
Application.DisplayAlerts = True
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = "Search Results"
For Each domainRange In rangeList ' goes through every value in worksheet trying to match what has been selected
If domainRange.value = strSelect Then
wks1.Rows(i).EntireRow.Copy ' copys the row that results was found in
emptyRow = WorksheetFunction.CountA(ws.range("A:A")) + 1 ' finds next empty row
ws.Paste (ws.Cells(emptyRow, 1)) 'pastes the contents
End If
i = i + 1
Application.CutCopyMode = False
Next domainRange
ws.range("A1:Q2").Columns.AutoFit 'auto fit the columns width depending on what is in the a1 to q1 cell
Else
MsgBox "No Results", vbInformation, "No Results" 'display messgae box if nothing is found
Exit Sub
End If
End If
End Sub