首页 文章

Excel VBA循环列和复制数据

提问于
浏览
0

我需要一些帮助,我正在尝试编写一些代码 . 我在VBA方面不是很有经验,我认为一个VLookup是我需要的,但在考虑之后 . 我认为Find循环工作更好 .

在sheet1上会有一个按钮单击 .

代码将需要执行以下操作,在工作表“全局”中使用列B和搜索范围,每行将具有不同的值,它将需要逐行搜索单元格值,如果找到匹配则在工作表“详细信息”中复制H,F和E列中的数据并粘贴到Global工作表中的O,P和Q列中 . H = O,E = P,D = Q.循环直到第一个空行 .

在详细信息表中,如果没有与详细信息匹配的数据,则在列B中,该行将被删除 .

For Example:

全球之前:
enter image description here

详情之前:
enter image description here

After Code has run:

全球之后:
enter image description here

详情之后:
enter image description here

希望这足以解释它,因为您可以看到它已找到匹配数据并将其复制到相关行,所有非匹配数据都已删除 .

我目前没有代码,因为如果我诚实,我不知道从哪里开始!非常感谢所有帮助!!

1 回答

  • 1

    试试这个 . 请注意,如果找到行中的值,您将需要一个空列暂时保留标记 - 在我的示例中,我使用了“I”列,如果它不为空,则需要修改它 .

    Private Sub pasteValues()
    Dim i, j, lastG, lastD As Long
    
    ' find last row
    lastG = Sheets("Global").Cells(Rows.Count, "B").End(xlUp).Row
    lastD = Sheets("Details").Cells(Rows.Count, "B").End(xlUp).Row
    
    ' loop over values in "Global"
    For i = 1 To lastG
        lookupVal = Sheets("Global").Cells(i, "B") ' value to find
    
        ' loop over values in "details"
        For j = 1 To lastD
            currVal = Sheets("Details").Cells(j, "B")
    
            If lookupVal = currVal Then
                Sheets("Global").Cells(i, "O") = Sheets("Details").Cells(j, "H")
                Sheets("Global").Cells(i, "P") = Sheets("Details").Cells(j, "E")
                Sheets("Global").Cells(i, "Q") = Sheets("Details").Cells(j, "D")
                ' mark the row
                Sheets("Details").Cells(j, "I") = "marked"
    
            End If
        Next j
    Next i
    
    ' loop over rows in "details" and delete rows which have not been marked
    For j = 1 To lastD
        If Sheets("Details").Cells(j, "I") <> "marked" Then
            ' delete unmarked rows
            Sheets("Details").Cells(j, "A").EntireRow.Delete
            If Sheets("Details").Cells(j, "B") <> "" Then
                j = j - 1 ' revert iterator so it doesn't skip rows
            End If
        Else:
            ' remove the mark
            Sheets("Details").Cells(j, "I") = ""
        End If
    Next j
    End Sub
    

相关问题