根据输入的日期将具有特定列的行复制到其他工作表

时间:2019-01-30 02:21:50

标签: excel vba

我有一个现有的VBA代码,如果标识符列标记为“ X”,则会复制行。现在,我希望它基于用户输入的日期范围。有人可以帮我将现有代码转换为所需的代码吗?谢谢!

Sub CopyRow()

Application.ScreenUpdating = False
Dim x As Long, MaxRowList As Long, MaxRowList2 As Long, S As String, wsSource As Worksheet, wsTarget As Worksheet, S2 As Long

Set wsSource = ThisWorkbook.Worksheets("Sheet 1 - RAW")
Set wsTarget = ThisWorkbook.Worksheets("Staging")
iCol = 1
MaxRowList = wsSource.Cells(Rows.Count, iCol).End(xlUp).Row
MaxRowList2 = wsTarget.Cells(Rows.Count, iCol).End(xlUp).Row
    S2 = 8

wsTarget.Range("A8:H22").ClearContents

For x = 4 To MaxRowList
    If InStr(1, wsSource.Cells(x, 19), "X") Then
        wsTarget.Cells(S2, 1).Value = wsSource.Cells(x, 1).Value
        wsTarget.Cells(S2, 4).Value = wsSource.Cells(x, 2).Value
        wsTarget.Cells(S2, 5).Value = wsSource.Cells(x, 10).Value
        wsTarget.Cells(S2, 6).Value = wsSource.Cells(x, 16).Value
        wsTarget.Cells(S2, 7).Value = wsSource.Cells(x, 18).Value
        wsTarget.Cells(S2, 8).Value = wsSource.Cells(x, 17).Value
        S2 = S2 + 1
        End If
Next

Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

您需要修改if语句。

If InStr(1, wsSource.Cells(x, 19), "X") Then

将成为

If wsSource.Cells(x, ColumnThatContainsTheDate).value > OlderDate and wsSource.Cells(x, 19).value < NewerDate Then

现在,您的问题将变成您希望用户如何选择日期?他可以动态选择(使用日历),仅是普通输入框还是基于单元格值的形式?您想要该日期之前还是之后的所有商品,还是想要两个日期之间的商品?只需根据您的需要调整语句即可。