Excel VBA在搜索时显示多结果

时间:2019-02-24 18:28:46

标签: excel vba

我有一张装满数据的表,如果我可以搜索所需的数据,将会更容易。

像SQL查询一样:

SELECT * FROM table_name WHERE Name='test'

因此,我找到了该脚本,该脚本部分适合我的情况。

Sub Zoek()

Dim erow As Long
Dim ws As Worksheet
Dim Lastrow As Long
Dim count As Integer
Dim resultrow As Integer

resultrow = 11

Lastrow = Sheets("Klanten").Cells(Rows.count, 1).End(xlUp).Row

count = 0
For x = 5 To Lastrow
    If Sheets("Klanten").Cells(x, 2) = Sheet1.Range("C6") Then
        Sheet1.Range("C11") = Sheets("Klanten").Cells(x, 1)
        Sheet1.Range("B11") = Sheets("Klanten").Cells(x, 2)
        Sheet1.Range("D11") = Sheets("Klanten").Cells(x, 11)
        count = count + 1
End If

Next x

End Sub

这段代码的问题在于,当同一搜索查询多次出现时,它将被覆盖,并且只有该搜索的最后一次匹配才会显示在单元格(B11,C11,D11)中。

>

我怎样才能使每个匹配项都显示在(B11-Bxx,C11- Cxx,D11- Dxx)中?

我知道可能已经有人问过这个问题,但是解决方案似乎太先进了。

我在VBA中是个菜鸟,所以我不知道如何实现这些解决方案。

如果有人可以向我提供此代码的解决方案,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

由于您已经具有该“ count”变量:

For x = 5 To Lastrow
    If Sheets("Klanten").Cells(x, 2) = Sheet1.Range("C6") Then
        Sheet1.Range("C11").Offset(count) = Sheets("Klanten").Cells(x, 1)
        Sheet1.Range("B11").Offset(count) = Sheets("Klanten").Cells(x, 2)
        Sheet1.Range("D11").Offset(count)= Sheets("Klanten").Cells(x, 11)
        count = count + 1
    End If

Next x

答案 1 :(得分:0)

下面的代码对您有用。

 Sub Zoek()

Dim erow As Long
Dim ws As Worksheet
Dim Lastrow As Long
Dim count As Integer
Dim resultrow As Integer

resultrow = 11

Lastrow = Sheets("Klanten").Cells(Rows.count, 1).End(xlUp).Row

count = 11
For x = 5 To Lastrow
If Sheets("Klanten").Cells(x, 2) = Sheet1.Range("C6") Then
    Sheet1.cells(count,1) = Sheets("Klanten").Cells(x, 1)
    Sheet1.cells(count,2) = Sheets("Klanten").Cells(x, 2)
    Sheet1.cells(count,11) = Sheets("Klanten").Cells(x, 11)
    count = count + 1
End If

Next x

End Sub