FindNext - 返回多个匹配(稍作修改)

时间:2017-05-16 06:58:32

标签: excel vba excel-vba

很高兴成为这个论坛的一员。好的,所以我的问题陈述是这样的:

我有2个Excel文件:
一个是主文件,其中包含所有唯一服务器的列表,另一个是数据库文件,其中应用程序映射到这些服务器。请注意,在数据库文件中,服务器条目不是唯一的(因为同一服务器可以托管多个应用程序)。

问题是我现在必须找到"其中主文件中的每个服务器都位于"数据库"文件,并返回应用程序的相应名称。由于服务器上可以有多个应用程序,我想在同一行(相邻列)中返回应用程序的所有名称。

例:
如果服务器的名称是主服务器中的ServerA,并且在第二个文件中有3个应用程序(A,B和C)映射到此,则我的主文件现在应该在脚本之后如下所示:

服务器A:A B C

我的代码似乎只返回两个匹配项。它并没有超出这个范围,我已经考虑了很长一段时间了,并在整个论坛上进行了搜索。使用的逻辑有什么问题吗?请帮忙!

以下是我使用的代码:

    Dim FindWord As String, Loc As Range
    Dim aCell As Range

    Dim database As Worksheet
    Dim mastersheet As Worksheet
    Set database = Workbooks("DataBase09052017.xlsm").Worksheets("Sheet1")
    Set mastersheet = Workbooks("EAS Apps Migration - Master Data Sheet_v2.0.xlsm").Worksheets("EAS Applications")

    Dim x, y As Integer
    x = 2
    y = 17

    Dim a, b, ctr, c As Integer
    a = 2
    b = 23
    c = 17

    Do Until x = 885
        y = 17
        FindWord = database.Cells(x, y).Value      
        Set Loc = mastersheet.Range("W2 : W6344").Find(What:=FindWord)

        If Not Loc Is Nothing Then
            database.Cells(x, y + 1).Value = mastersheet.Cells(Loc.Row, 1).Value
            Set aCell = Loc
            Do
                Set aCell = mastersheet.Range("W2: W6344").FindNext(aCell)
                y = y + 1
                If Not aCell Is Nothing Then
                    database.Cells(x, y + 1).Value = mastersheet.Cells(aCell.Row, 1).Value
                End If
            Loop While aCell <> Loc
        End If
        x = x + 1
    Loop

End Sub

1 个答案:

答案 0 :(得分:0)

你能试试吗?我认为你的循环比较是关闭的(比较Loc和aCell),你可能想要指定一些除了&#39;什么&#39;以外的查找参数。

Sub x()

Dim FindWord As String, Loc As Range
Dim aCell As String

Dim database As Worksheet
Dim mastersheet As Worksheet
Set database = Workbooks("DataBase09052017.xlsm").Worksheets("Sheet1")
Set mastersheet = Workbooks("EAS Apps Migration - Master Data Sheet_v2.0.xlsm").Worksheets("EAS Applications")

Dim x As Long, y As Long
x = 2
y = 17

Dim a As Long, b As Long, ctr As Long, c As Long
a = 2
b = 23
c = 17

Do Until x = 885
    y = 17
    FindWord = database.Cells(x, y).Value
    Set Loc = mastersheet.Range("W2:W6344").Find(What:=FindWord)
    If Not Loc Is Nothing Then
        aCell = Loc.Address
        Do
            database.Cells(x, y + 1).Value = mastersheet.Cells(Loc.Row, 1).Value
            Set Loc = mastersheet.Range("W2:W6344").FindNext(Loc)
            y = y + 1
        Loop While aCell <> Loc.Address
    End If
    x = x + 1
Loop

End Sub