用于搜索列并对其进行排序的VBA代码

时间:2017-01-25 13:30:10

标签: excel vba excel-vba

我正在编写一个VBA代码,必须在工作表上找到特定的列并在特定的citeria上对其进行排序。这是我的代码

Sub SortExchangesEurope()

    Dim intCounter As Integer
    Dim rngExchange As Range
    intCounter = 1

    Do While Worksheets("Sheet1").Cells(2, intCounter) <> ""
        If Worksheets("Sheet1").Cells(2, intCounter).Value = "Exchange" Then
            With Worksheets("Sheet1")
                Set rngExchange = .Range(.Cells(2, intCounter), .Cells(2, intCounter))
               MsgBox intCounter
             End With
        End If

        intCounter = intCounter + 1
    Loop

    Worksheets("Sheet1").Range("$A$2:$AP$778").AutoFilter Field:=intCounter, Criteria1:=Array( _
        "XBEL", "XBUD", "XBSE", "XQMH", "XWAR", _
        "BMEX", "XLIS", "XLIT", "XBUL", "ASEX", _
        "XDUB", "XBRU", "XLUX", "XSTO", "XSWX", _
        "XHEL", "XMOS", "MISX", "XCSE", "XVTX", _
        "IEPA", "XMIL", "XLIS", "BMEX", _
        "XLJU", "ASEX", "XRIS", "XBRA", "xlOn", _
        "XOSL", "XPAR", "XPRA", "XICE", "XIST", _
        "XTAL", "XMIL", "XTRN", "XBRU", "XLDN", _
        "XAMS", "XZAG", "XSWX", "XATH", "XMAD", "XOME", _
        "XMRV", "XADE", "XVTX", "XTAH", "RTSX", "XLTO", _
        "XDMI", "MFOX", "XMAD", "XMAT", "XTLX", "ICEU", _
        "XMON", "XTUR", "XBRD", "XEDX", "XOME", "XLIF"), Operator:=xlFilterValues

End Sub

第一部分查找名称所在的列,第二部分必须仅对包含给定代码的字段进行排序。这两个部分分别工作正常,但它们不能一起工作。

范围类的自动过滤失败 - 我收到此错误

1 个答案:

答案 0 :(得分:1)

在使用AutoFilterMode

之前,您必须先检查并设置AutoFilter
Sub SortExchangesEurope()
    Dim wS As Worksheet
    Dim intCounter As Integer
    Dim rngExchange As Range

    Set wS = Sheets("Sheet1")
    intCounter = 1

    With wS
        Do While .Cells(2, intCounter).Value <> "Exchange" Then
           intCounter = intCounter + 1
        Loop
        Set rngExchange = .Range(.Cells(2, intCounter), .Cells(2, intCounter))

        '.Activate
        '.Range("B2").Activate
        If Not .AutoFilterMode Then .AutoFilterMode = True

        .Range("$A$2:$AP$778").AutoFilter Field:=intCounter, Criteria1:=Array( _
            "XBEL", "XBUD", "XBSE", "XQMH", "XWAR", _
            "BMEX", "XLIS", "XLIT", "XBUL", "ASEX", _
            "XDUB", "XBRU", "XLUX", "XSTO", "XSWX", _
            "XHEL", "XMOS", "MISX", "XCSE", "XVTX", _
            "IEPA", "XMIL", "XLIS", "BMEX", _
            "XLJU", "ASEX", "XRIS", "XBRA", "xlOn", _
            "XOSL", "XPAR", "XPRA", "XICE", "XIST", _
            "XTAL", "XMIL", "XTRN", "XBRU", "XLDN", _
            "XAMS", "XZAG", "XSWX", "XATH", "XMAD", "XOME", _
            "XMRV", "XADE", "XVTX", "XTAH", "RTSX", "XLTO", _
            "XDMI", "MFOX", "XMAD", "XMAT", "XTLX", "ICEU", _
            "XMON", "XTUR", "XBRD", "XEDX", "XOME", "XLIF"), Operator:=xlFilterValues

    End With 'wS

End Sub