将基于条件的特定列中的单元格复制到下一个可用行中的另一列中

时间:2017-06-20 17:57:02

标签: excel vba excel-vba

我有两个工作表,“签名”和“四月”。 我想根据某些标准将列“Y”从“签名”复制到从下一个可用/空白行开始的列“A”中。 (就在现有数据下面。)

我对Y列的标准是,如果列L =来自“April”的单元格“D2”的月份和来自“ApriL”的单元格“D2”的年份...(所以现在D2是4/30/2017 ).. 然后将该单元格复制到“四月”的Col A的下一行并继续添加。

我的代码如下:

Dim sourceSht As Worksheet
Dim myrange As Range
Dim DestRow As Integer
Dim ws2 As Worksheet
Dim MonthVal As String

Range("D3").Select
ActiveCell.FormulaR1C1 = "=MONTH(R[-1]C)"
Range("D3").Select
Selection.NumberFormat = "General"
MonthVal = ActiveCell.Value

Set sourceSht = ThisWorkbook.Worksheets("Signed")
Set myrange = sourceSht.Range("Y1", Range("Y" & Rows.Count).End(xlUp))
Set ws2 = Sheets("April")
DestRow = ws2.Cells(Rows.Count, "A").End(xlUp).Row + 1

For Each rw In myrange.Rows
  If rw.Cells(12).Value = MonthVal Then
    myrange.Value.Copy Destinations:=Sheets(ws2).Range("A" & DestRow)
  End If  
Next rw

1 个答案:

答案 0 :(得分:1)

试试这个:

Dim sourceSht As Worksheet
Dim myrange As Range
Dim DestRow As Integer
Dim ws2 As Worksheet
Dim MonthVal As String
Dim rw As Range

Range("D3").Select
ActiveCell.FormulaR1C1 = "=MONTH(R[-1]C)"
Range("D3").Select
Selection.NumberFormat = "General"
MonthVal = ActiveCell.Value

Set sourceSht = ThisWorkbook.Worksheets("Signed")
Set myrange = sourceSht.Range("Y1:Y" & sourceSht.UsedRange.Row - 1 + sourceSht.UsedRange.Rows.Count)
Set ws2 = Sheets("April")
DestRow = ws2.Cells(Rows.Count, "A").End(xlUp).Row ' + 1

For Each rw In myrange '.Rows
    If sourceSht.Cells(rw.Row, 12).Value = MonthVal Then
        DestRow = DestRow + 1
        rw.Copy Destination:=Sheets("April").Range("A" & DestRow)
    End If
Next rw

编辑:修复第15行(从Set myrange = sourceSht.Range("Y1:y" & sourceSht.UsedRange.Rows.Count)Set myrange = sourceSht.Range("Y1:Y" & sourceSht.UsedRange.Row - 1 + sourceSht.UsedRange.Rows.Count))的潜在漏洞,以防顶部有未使用的行。