【问题标题】:How to search for matching dates in two different sheets and then copy corresponding data from source sheet to destination sheet如何在两个不同的工作表中搜索匹配的日期,然后将相应的数据从源工作表复制到目标工作表
【发布时间】:2019-10-10 12:58:33
【问题描述】:

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

一些条件:

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

我是 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变量类型不匹配

【问题讨论】:

  • 正确缩进你的代码将极大地帮助解决诸如“next wihtout for”错误之类的问题。此外,虽然这不是你的问题,但在你的代码中avoid using Activate and Select 总是一个好主意
  • 对于初学者,您的end if 必须在next next 之前...我将编辑您的代码,以便您查看问题...
  • 修改获得批准后,查看格式如何影响您的代码以及发现问题的难易程度。
  • 好的,感谢您的提示 - 现在的错误是:关于变量 'i' @cybernetic.nomad 的“运行时错误'13':类型不匹配”。这是因为我错误地引用了单元格值(或者变量类型应该是日期?)
  • 您将i 定义为double.. 即一个数字...我认为这应该是date

标签: excel vba


【解决方案1】:

用更正的格式更新了代码..似乎你明白你哪里出错了......

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多