需要vba代码才能在一个工作表中搜索多个数据

时间:2017-01-20 05:05:19

标签: sql vba excel-vba access excel

您好我正在寻找一个vba代码来搜索一个工作表中的多个数据,然后将对应信息填充到一个新的工作表,这里是示例:

在我有的数据表中

Customer Number Customer Name   Invoice Date    Invoice Amount
1                ABC            4/17/2012       $5,000.00 
2                FGI            4/18/2012       $4,560.00 
3                NEC            4/19/2012       $687.00 
4                IEO            4/20/2012       $158.00 
5                PWO            4/21/2012       $1,549.00 
4                IEO            4/22/2012       $3,247.00 
1                ABC            4/23/2012       $1,590.00 
2                FGI            4/24/2012       $165.00 
3                NEC            4/25/2012       $158.00 
6                VCW            4/26/2012       $3,777.00 

当我搜索客户名称时:

ABC
FGI
NEC
IEO
PWO

它会在新的工作表中显示结果,如:

Customer Number Customer Name   Invoice Date    Invoice Amount
1                ABC            4/17/2012       $5,000.00 
1                ABC            4/23/2012       $1,590.00 
2                FGI            4/18/2012       $4,560.00
2                FGI            4/24/2012       $165.00 
3                NEC            4/19/2012       $687.00 
3                NEC            4/25/2012       $158.00 
4                IEO            4/20/2012       $158.00 
4                IEO            4/22/2012       $3,247.00 
5                PWO            4/21/2012       $1,549.00 

1 个答案:

答案 0 :(得分:1)

Data Sheet

Search Result Sheet

将一个工作表命名为数据和另一个工作表搜索结果。请注意搜索栏。

子搜索()

 Dim i, j, newsheet_rownum
 newsheet_rownum = 2
 Sheets("Search Result").Range("A2:D65536").ClearContents

 For i = 2 To 65536
    If Len(Cells(i, 6)) = 0 Then
        Exit For
    End If

    For j = 2 To 65536

        If (Cells(i, 6) = Cells(j, 2)) Then
            Sheets("Search Result").Cells(newsheet_rownum, 1) = Sheets("Data").Cells(j, 1)
            Sheets("Search Result").Cells(newsheet_rownum, 2) = Sheets("Data").Cells(j, 2)
            Sheets("Search Result").Cells(newsheet_rownum, 3) = Sheets("Data").Cells(j, 3)
            Sheets("Search Result").Cells(newsheet_rownum, 4) = Sheets("Data").Cells(j, 4)
            newsheet_rownum = newsheet_rownum + 1
        End If

    Next j

 Next i
 MsgBox "Job Done"

End Sub