如何在两个不同的工作表中搜索匹配的日期,然后将相应的数据从源工作表复制到目标工作表

时间:2019-05-23 23:00:03

标签: excel vba

我想在报告电子表格(A)中搜索日期,然后在数据源电子表格(B)中搜索该日期。找到后,我想将数据(与日期位于同一行)复制并粘贴到报表电子表格(A)中的相应日期中。

某些条件:

  • 使用后,将无法重复使用数据源电子表格(B)中的数据 因此,我想搜索具有相同日期的下一行...
  • 这就是我使用宏的原因(否则,我只会使用 vlookup)

我是VBA的新手,所以我一直尝试结合使用某些循环,但未成功

我想知道是否有更简单的方法?

Sub DataToRegister()


Dim Row As Double 'row is the row variable for the destination spreadsheet
Dim i As Double
Dim x As Integer 'x is the row variable for the source spreadsheet


For Row = 1 To 825

    i = Sheets("Register Data Fields").Cells(Row, 1)

        While i <> DateSerial(1900, 1, 0)
        'DateSerial(1900, 1, 0) --> this is the default for no data in the field, i.e. i want to skip these

            For x = 1 To 825

                If Sheets("HANSON DATA").Cells(x, 2) = Sheets("Register Data Fields").Cells(Row, 1) Then
                Sheets("HANSON DATA").Select
                Cells(x, 1).Select
                Selection.Copy
                Sheets("Register Data Fields").Select
                Cells(Row, 22).Select
                ActiveSheet.Paste
                Application.CutCopyMode = False

                Next

            Next

        Wend

End If


End Sub

我遇到的错误包括:

  • Next(不含for x2
  • wend(无while
  • i不匹配变量类型

1 个答案:

答案 0 :(得分:0)

具有正确格式的更新代码..看来您了解要出问题的地方...

Sub DataToRegister()


    Dim Row As Long
    Dim i As Date
    Dim x As Long


    For Row = 1 To 825

        i = Sheets("Register Data Fields").Cells(Row, 1)

        If i <> DateSerial(1900, 1, 0) Then
        'DateSerial(1900, 1, 0) --> this is the default for no data in the field, i.e. i want to skip these

            For x = 1 To 825

                If Sheets("HANSON DATA").Cells(x, 2) = Sheets("Register Data Fields").Cells(Row, 1) Then
                    Sheets("HANSON DATA").Select
                    Cells(x, 1).Select
                    Selection.Copy
                    Sheets("Register Data Fields").Select
                    Cells(Row, 22).Select
                    ActiveSheet.Paste
                    Application.CutCopyMode = False
                End If

            Next x

        End If

    Next Row


End Sub