【问题标题】:Copy Rows to Another Sheet Based on Date Range Multiple Times根据日期范围多次将行复制到另一个工作表
【发布时间】:2019-01-07 19:10:36
【问题描述】:

我有一个大约 15 张工作表的 Excel 工作簿。我正在寻找一种根据 K 列中的日期范围将行复制到新工作表的方法。

例子:

工作表 1: 日期范围 (1/1/15 - 1/1/18) -> 将时间范围内的所有行复制到工作表 4

工作表 2: 日期范围 (1/1/15 - 1/1/18) -> 将时间范围内的所有行复制到工作表 5

工作表 3: 日期范围 (1/1/15 - 1/1/18) -> 将时间范围内的所有行复制到工作表 6

等等

一次完成一张工作的代码,但我希望它一次完成:

Sub Date_Sample()
    Application.ScreenUpdating = False
    On Error GoTo M
    Dim i As Long
    Dim ans As Date
    Dim anss As Date
    Dim Lastrow As Long
    Dim Lastrowa As Long
    ans = InputBox("Start Date Is")
    anss = InputBox("End Date Is")
    Lastrowa = Sheets("Sheet1").Cells(Rows.Count, "K").End(xlUp).Row
    Lastrowb = Sheets("Sheet4").Cells(Rows.Count, "K").End(xlUp).Row + 1
    For i = 1 To Lastrowa
        If Cells(i, "K").Value >= ans And Cells(i, "K").Value <= anss Then
            Rows(i).Copy Destination:=Sheets("Sheet4").Rows(Lastrowb)
            Lastrowb = Lastrowb + 1
            Rows(i).EntireRow.Delete
            i = i - 1
        End If
    Next i
    Application.ScreenUpdating = True
    Exit Sub
M:
    MsgBox "Wrong Date"
    Application.ScreenUpdating = True
End Sub

我尝试为其他工作表添加另一个 For 语句,但没有成功。

【问题讨论】:

  • 1) 使用自动筛选来获取数据。 2) 循环遍历每个工作表。 3) 在工作表名称上使用 Select Case 来确定将在哪个工作表上复制数据。

标签: excel vba


【解决方案1】:

工作表数组

添加变量:

  • j - 表格计数器
  • str1 - 要复制的工作表列表
  • str2 - 要复制到的工作表列表
  • vnt1 - 要从中复制的工作表数组
  • vnt2 - 要复制到的工作表数组

代码

Sub Date_Sample()

    Application.ScreenUpdating = False

    On Error GoTo M

    Const str1 As String = "Sheet1,Sheet2,Sheet3"
    Const str2 As String = "Sheet4,Sheet5,Sheet6"

    Dim vnt1 As Variant
    Dim vnt2 As Variant
    Dim i As Long
    Dim j As Integer
    Dim ans As Date
    Dim anss As Date
    Dim Lastrow As Long
    Dim Lastrowa As Long

    ans = InputBox("Start Date Is")
    anss = InputBox("End Date Is")
    vnt1 = Split(str1, ",")
    vnt2 = Split(str2, ",")

    For j = 0 To UBound(vnt1)
        Lastrowa = Sheets(vnt1(j)).Cells(Rows.Count, "K").End(xlUp).Row
        Lastrowb = Sheets(vnt2(j)).Cells(Rows.Count, "K").End(xlUp).Row + 1
        For i = 1 To Lastrowa
            With Sheets(vnt1(j))
                If .Cells(i, "K").Value >= ans _
                        And .Cells(i, "K").Value <= anss Then
                    .Rows(i).Copy Destination:=Sheets(vnt2(j)).Rows(Lastrowb)
                    Lastrowb = Lastrowb + 1
                    .Rows(i).EntireRow.Delete
                    i = i - 1
                End If
            End With
        Next i
    Next j

    Application.ScreenUpdating = True

    Exit Sub
M:
    MsgBox "Wrong Date"
    Application.ScreenUpdating = True
End Sub

【讨论】:

  • 这很好用,但有一个例外。 Sheet1 不会复制到 Sheet4。代码似乎以 Sheet2 开头。
  • @Searshore:抱歉,只需将 For j = 1 to ... 更改为 For j=0 to...。这些数组是从 0 开始的。
  • 完美!非常感谢!还在学习数组。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 2016-04-25
  • 2020-04-09
相关资源
最近更新 更多