简体   繁体   中英

how to get data from a excel sheet to another when two criteria is true using vba

I have put 20 different project data in one excel sheet1 with s.no, name, date, description, amount, and cheque Number. now I want to filter this data in another sheet2 with name and specified date using VBA? please someone help me?

You can do this with 1 line of code & a couple of named ranges, assuming you have Office 365 version Excel.

Sub Filter()
    Sheets("Sheet2").Range("B3").ActiveCell.Formula2R1C1 = "=FILTER(data,--(INDEX(data,0,2)=name_filter)*(INDEX(data,0,3)=date_filter))"
End Sub

This references 3 named ranges which you need to create before running the code:

  • " data " is the named range referring to these cells in Sheet 1
  • " name_filter " and " date_filter " are 2 cells you want to use to filter this table - these are in Sheet2 which is also where the filtered table will be

You can find out more about named ranges here: Define and Use Named Ranges . This only needs to be done once right at the beginning, the macro can then be run again and again without changing your named ranges. If rows in your data are to change (eg new items added/older removed etc.) then you can always create a dynamic range: Exceljet dynamic ranges .

source data: 表 1 和“数据”命名范围

user inputs name_filter and date_filter (J2-3 respectively) and runs macro code above to this table in Sheet 2: 表 2

Sub Button2_Click()
'
' Macro1 Macro
'

Dim rg As Range

Set rg = ThisWorkbook.Worksheets("Filterdata").Range("A1").CurrentRegion
   rg.Offset(1).ClearContents
        
Dim rgData As Range, rgCriteria As Range, rgFilterdata As Range

Set rgData = ThisWorkbook.Worksheets("Data").Range("A4").CurrentRegion

Set rgCriteria = ThisWorkbook.Worksheets("Data").Range("A1").CurrentRegion

Set rgFilterdata = ThisWorkbook.Worksheets("Filterdata").Range("A1:G2000")

    rgData.AdvancedFilter xlFilterCopy, rgCriteria, rgFilterdata, Unique:=False
End Sub

This is the code that I want to create for the advanced filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM