Excel迭代2张中的行并捕获特定行上的数据

时间:2018-05-15 18:26:49

标签: excel vba excel-vba

任何人都能看到我在这里做错了什么? 我只需要在从一张纸到另一张纸的匹配上获得一些单元格内容。

Sub CommandButton1_Click()

Dim i As Integer
Dim j As Integer
Dim myValue As String
i = 2
j = 3

Do While Worksheets("sheet1").Cells(i, 1).Value <> ""
    myValue = Worksheets("sheet1").Cells(i, 1).Value
    Do While Worksheets("sheet2").Cells(j, 1).Value <> ""
        If Worksheets("sheet2").Cells(j, 1).Value = myValue Then

            If (Worksheets("sheet1").Cells(i, 4).Value = Worksheets("sheet2").Cells(j, 3).Value) And (Worksheets("sheet1").Cells(i, 5).Value = Worksheets("sheet2").Cells(j, 4).Value) And (Worksheets("sheet1").Cells(i, 6).Value = Worksheets("sheet2").Cells(j, 5).Value) And (Worksheets("sheet1").Cells(i, 7).Value = Worksheets("sheet2").Cells(j, 6).Value) Then

                Worksheets("sheet2").Cells(j, 18).Value = Worksheets("sheet1").Cells(i, 3).Value
            End If







        End If
        j = j + 1 'go to the next row in your second sheet
    Loop

    i = i + 1 'go to the next row in your first sheet
    j = 3 'now we are going to iterate the next row of the first sheet, so we want to reset the position in our second sheet
Loop
End Sub

现在它没有编辑我真正长IF语句之后指定的单元格。

1 个答案:

答案 0 :(得分:0)

我尝试编写一些代码来完成你的任务,但我真的不完全理解你的问题:

Sub myFunc()

    Dim i As Integer
    Dim j As Integer
    Dim myValue As String
    i = 1
    j = 1

    Do While Worksheets("myFirstSheet").Cells(i, 1).value <> "" 'I assume that when a cell is empty then we reached the end of your table
        myValue = Worksheets("myFirstSheet").Cells(i, 1).value 'I save the value of the cell in a variable

        Do While Worksheets("mySecondSheet").Cells(j, 1).value <> "" 'I assume that when a cell is empty then we reached the end of your table
            If Worksheets("mySecondSheet").Cells(j, 1).value = myValue Then 'if that value equals one of the cells of your second sheet...
                doSomethingFunc 'we have to write it
            End If
            j = j + 1 'go to the next row in your second sheet
        Loop

        i = i + 1 'go to the next row in your first sheet
        j = 1 'now we are going to iterate the next row of the first sheet, so we want to reset the position in our second sheet
    Loop

End Sub

现在,此代码遍历第一张工作表的所有记录,并且在第二张工作表中遇到的记录等于第一张工作表之一调用函数doSomethingFunc。它比较了两张纸的第一列。 如果工作表的名称发生变化,那么你最好创建一个userForm(如果你需要我可以解释,但不要担心这很容易)。

现在我们必须写doSomethingFunc。那么,当它找到两个等于行时你想要它发生什么?

抱歉我的英语不好!

编辑1:

这些是虚构的数据库:

sheet1

sheet2