根据单元格的值选择行并将它们粘贴到新工作表中excel vba

时间:2015-06-26 14:54:04

标签: excel vba excel-vba

我正在尝试根据A列中的值复制整行。标准将是昨天的日期。宏需要保持动态,因为每天运行此宏并使用前一天的数据。以下是我到目前为止的情况:

    Sub SelectRowsByDate()

    Dim WS1 As Worksheet
    Set WS1 = ThisWorkbook.Sheets("Test")

    Dim YesterdayDate As Date
    Dim loopCounter As Long
    YesterdayDate = Date - 1
    For loopCounter = 1 To Rows.Count
       If Cells(i, 1).Value = YesterdayDate Then
       Rows(i).Select

    End If

    End Sub

2 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。首先,你需要每个For的下一个。你可以试试这个:

Sub improved()

Dim irow As Integer
Dim x As Integer
Dim dDate As Date

x = 1
For irow = 1 To WorksheetFunction.CountA(Columns(1))
    dDate = Cells(irow, 1).Value
    If dDate = Date - 1 Then
        Debug.Print Worksheets("Sheet1").Cells(irow, 1).Value
        Worksheets("Sheet1").Cells(irow, 1).EntireRow.Copy
        Sheet2.Range("A" & x).PasteSpecial xlPasteAll
        x = x + 1
    End If
Next

End Sub

它使用了EntireRow函数,这是您所需要的。您需要将您正在处理的工作表名称更改为Sheet1和Sheet2。

我希望这会有所帮助。

答案 1 :(得分:0)

让我们在以前的任务中将其作为一个想法。
在宏功能中1-使用这样的东西来循环主表及其传送的数据

For I = 4 To Worksheets(Isheet).Rows.Count
  If Worksheets(Isheets).Cells(I, 7).Value <> "" Then
    For N = 1 To Worksheets.Count-1
        If Worksheets(N).Name = Worksheets(Isheets).Cells(I, 7).Value Then
          // Insert the Current row in this sheet 
          Exit For
        End If
    Next N
    If N >= Worksheets.Count 
      // in this case the is new, so here will make a new Sheet for his rows and then insert this row in it.
      Worksheets.Add ,,
    End IF
  End If
Next N

任何停止任务的评论都是我。 祝你好,