VBA运行时错误' 1004'。 Range类的AutoFilter方法失败

时间:2016-04-25 10:47:22

标签: excel vba excel-vba runtime runtime-error

每当我执行我的宏(下面)搜索输入搜索框的字符串时,我都会收到运行时错误' 1004'。 Range类的AutoFilter方法失败。我已经尝试在这里寻找这个问题的答案了一段时间,但似乎没有什么能为我提供解决方案。

当我点击' Debug'它突出显示了代码的以下部分。

    DataRange.AutoFilter _
    Field:=myField, _
    Criteria1:=SearchString, _
    Operator:=xlAnd

我意识到这不是很多信息,但任何帮助都会非常感激。

P.S。我是VBA的一个完整的新手,并从一个网站上复制了代码,该网站分步指导了在Excel中创建搜索过滤器。

Sub SearchBox()

Dim myButton As OptionButton
Dim SearchString As String
Dim ButtonName As String
Dim sht As Worksheet
Dim myField As Long
Dim DataRange As Range
Dim mySearch As Variant

'Load Sheet into A Variable
  Set sht = ActiveSheet

'Unfilter Data (if necessary)
  On Error Resume Next
    sht.ShowAllData
  On Error GoTo 0

'Filtered Data Range (include column heading cells)
  Set DataRange = sht.Range("A5:Z40000") 'Cell Range
  'Set DataRange = sht.ListObjects("Table1").Range 'Table

'Retrieve User's Search Input
  mySearch = sht.Shapes("UserSearch").TextFrame.Characters.Text 'Control Form
  'mySearch = sht.OLEObjects("UserSearch").Object.Text 'ActiveX Control
  'mySearch = sht.Range("A1").Value 'Cell Input

'Determine if user is searching for number or text
  If IsNumeric(mySearch) = True Then
    SearchString = "=" & mySearch
  Else
    SearchString = "=*" & mySearch & "*"
  End If

'Loop Through Option Buttons
  For Each myButton In sht.OptionButtons
    If myButton.Value = 1 Then
      ButtonName = myButton.Text
      Exit For
    End If
  Next myButton

'Determine Filter Field
  On Error GoTo HeadingNotFound
    myField = Application.WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0)
  On Error GoTo 0

'Filter Data
  DataRange.AutoFilter _
    Field:=myField, _
    Criteria1:=SearchString, _
    Operator:=xlAnd

'Clear Search Field
  sht.Shapes("UserSearch").TextFrame.Characters.Text = "" 'Control Form
  'sht.OLEObjects("UserSearch").Object.Text = "" 'ActiveX Control
  'sht.Range("A1").Value = "" 'Cell Input

Exit Sub

'ERROR HANDLERS
HeadingNotFound:
  MsgBox "The column heading [" & ButtonName & "] was not found in cells " & DataRange.Rows(1).Address & ". " & _
    vbNewLine & "Please check for possible typos.", vbCritical, "Header Name Not Found!"

End Sub

1 个答案:

答案 0 :(得分:0)

检查myField的值,它必须介于1到26之间,因为您的范围是A - > ž。