使用VBA复制行并粘贴到不同的表中(代码已编辑)

时间:2017-02-15 10:02:32

标签: excel vba excel-vba

我有以下代码从用户获取日期输入。我想做的是:

  • 查找工作表COl K中输入日期之前的所有日期"延迟"
  • 复制整行并将其粘贴到名为"上一页"的其他工作表中。

我的代码:

Sub Previousweek()
Dim userdate

userdate = InputBox("Enter the date", "Enter Date", Date)
 If IsDate(userdate) Then
  'logic here
    End If

End Sub

更新代码:

Sub Previousweek()
Dim userdate

userdate = InputBox("Enter the date", "Enter Date", Date)
Dim rng As Range, cell As Range
Set rng = Range("K2:K200")
For Each cell In rng
  If cell.Value < userdate Then
    cell.EntireRow.Copy
    Sheets("Previous").Range("A65536").End(xlUp).Offset(1, 0).Select
            Sheets("Previous").Paste
        End If
     Next cell
   End Sub

由于下标超出范围,因此在下面一行显示错误:

Sheets("Previous").Range("A65536").End(xlUp).Offset(1, 0).Select

2 个答案:

答案 0 :(得分:2)

只需更改With ThisWorkbook.Sheets("Previous")中的上一个 到要粘贴数据的工作表的名称!

Sub Previousweek()
    Dim UserDate As String
    Dim CeLL As Range
    UserDate = InputBox("Enter the date", "Enter Date", Date)

    If IsDate(UserDate) Then
        With ThisWorkbook.Sheets("Previous")
            For Each CeLL In ThisWorkbook.Sheets("Latency").Range("K2:K200").Cells
                If CeLL.Value < UserDate Then
                    CeLL.EntireRow.Copy .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
                End If
            Next CeLL
        End With 'ThisWorkbook.Sheets("Previous")
    Else
    End If
End Sub

答案 1 :(得分:1)

查找较小的日期伪代码

Dim rng As Range, cell As Range
Set rng = Range("K2:K200")
For Each cell In rng
  if cell.value < userdate then
    //TODO copy to previous
  end if
Next cell