簡體   English   中英

VBA 代碼為 select 過濾器值從一張表的下拉菜單中,並在另一張工作表的表格中應用過濾器 - Excel 2010

[英]VBA code to select filter value from drop down menu on one sheet and apply filter in a table on another worksheet - Excel 2010

Very novice, trying to write a VBA code in EXcel 2010 to select filter value from a drop down list located in cell A1 of Sheet1 and apply filter value on column 4 of a data range A7:S1000 located on Sheet2. 下面是插入到 Sheet1 中的代碼,我正在使用它,但沒有返回任何內容。 我在哪里弄錯了? 非常感謝。

Private Sub Worksheet_Change(ByVal Target As Range)
    ' Cell with dropdown where value to be selected
    Const DropDown = "a1"
    ' Sheet with data range to apply filter
    Const TableSheet = "Sheet2"
    ' Top left cell of the data range
    Const TableRange = "a7"
    If Not Intersect(Range(DropDown), Target) Is Nothing Then
        Application.EnableEvents = False
        If Range(DropDown).Value = "" Then
            Worksheets(TableSheet).ShowAllData
        Else
            Worksheets(TableSheet).Range(TableRange).AutoFilter _
                Field:=4, Criteria1:=Range(DropDown).Value
        End If
        Application.EnableEvents = True
    End If End Sub

@Scottyfrog 我希望我在上面的評論中提供的建議可以解決問題,但不幸的是它沒有。 作為替代方案,我以一種更易於理解的方式重寫了您的代碼。 我在我自己的電腦上測試過它似乎工作正常。

此外,您的問題的一個可能原因可能是過濾器找不到任何符合您的條件的值。 我在您的代碼中添加了一個測試,它會告訴您它是否找不到任何匹配的值。

讓我知道它是如何進行的,如果它有效,請提高答案。

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Range("A1"), Target) Is Nothing Then
 
    If Range("A1").Value = "" Then
        
    Worksheets("Sheet2").ShowAllData
    
    Else
    
        If Application.WorksheetFunction.CountIf(Worksheets("Sheet2").Range("D:D"), Range("A1")) = 0 Then
        
            MsgBox "The Filtered value doesn't exist in column D on sheet 2"
            
            Exit Sub
        
        End If
    
    Worksheets("Sheet2").Range("A7:S7").AutoFilter Field:=4, Criteria1:=Range("A1").Value
    
    End If
    
End If
  
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM