对于每个循环,其运行均未达到预期

时间:2019-05-27 09:23:28

标签: excel vba for-loop each

我在excel中有两张纸,一张是一个板,里面有几个单元格,里面有数字,另一张是引用(在前面的板上有数字),我需要在引用的同一行中写单元格在哪里位于。
image of the first board where are the references
image of the excel sheet that i have to write the location of each reference
my vba code

示例:

enter image description here

arm8.png是板子,而local.png是我编写单元格非本地化的地方

Option Explicit

Sub ciclo()

    Dim FindString As String
    Dim Rng As Range
    Dim matrixVal As Range

    Set matrixVal = Sheets("Localizações").Range("B1")
    FindString = matrixVal

    For Each Rng In matrixVal

        If Trim(FindString) <> "" Then

            With Sheets("Arm8").Range("A1:J10")

                Set Rng = .Find(What:=FindString, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)

                If Not Rng Is Nothing Then
                    'Application.Goto Rng, False
                    'MsgBox Rng.Column & " - " & Rng.Row
                Else
                    MsgBox "Nothing found"
                End If

            End With

            With Sheets("Localizações")
                .Range("C1:C9").Value = Rng.Column
                .Range("D1:D9").Value = Rng.Row
            End With

        End If

    Next Rng

End Sub

我希望local.png中的输出为C和D列

2-9
2-7
2-8
2-4
5-4
7 -4
5-9
9 -7
9-0

1 个答案:

答案 0 :(得分:1)

首先,正如我在评论中所说:

Set matrixVal = Sheets("Localizações").Range("B1")

matrixVal设置为一个单元格(准确地说是B1),因此您的For-Each循环没有任何单元格可以循环通过,因此只能运行一次。

第二,FindString需要在循环内更新,否则您将一遍又一遍地搜索相同的值。

最后,您不应该在循环内更新Rng变量,因为您已经在使用它遍历范围。您需要第二个类型为Range的变量。

您的代码应如下所示:

 Sub ciclo()

    Dim FindString As String
    Dim Rng As Range
    Dim cell As Range
    Dim matrixVal As Range

    Set matrixVal = ThisWorkbook.Worksheets("Localizacoes").Range("B1:B9")

    For Each cell In matrixVal
        FindString = cell.Value

        If Trim(FindString) <> "" Then

            With ThisWorkbook.Worksheets("Arm8").Range("A1:J10")

                Set Rng = .Find(What:=FindString, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)

                If Not Rng Is Nothing Then
                    With ThisWorkbook.Worksheets("Localizacoes")
                        .Cells(cell.Row, "C").Value = Rng.Column
                        .Cells(cell.Row, "D").Value = Rng.Row
                    End With
                Else
                    MsgBox "Nothing found"
                End If

            End With

        End If

    Next cell

End Sub
相关问题