简体   繁体   English

按日期复制和粘贴数据-Excel VBA

[英]Copy and paste data by date - excel vba

I need to move data from one sheet to another by the criteria date, but the selection that I made using IF only select the last cell that matches that criteria. 我需要在标准日期之前将数据从一张纸移到另一张纸,但是我使用IF所做的选择仅选择了与该标准匹配的最后一个单元格。

Here is what i got so far: 这是我到目前为止所得到的:

Sub Copiar()

Dim range1 As Range

Set range1 = Range("k56:k58")

For Each cell In range1
   If cell.Value = Range("R55").Value Then
      cell.Offset(0, 2).Select
      Selection.Copy
      Sheets("Plan2").Activate
      Range("r56").Select
      ActiveSheet.Paste
   End If
Next

End Sub

You are finding them all, the problem is that every answer overwrites R56 on the other sheet. 您正在找到所有这些,问题是每个答案都会覆盖另一张纸上的R56。 Here's code that advances that destination cell every repeat of the loop - and also avoids the bad practice of selecting and activating every sheet and cell you are working with: 以下代码可在循环的每个重复中使目标单元格前进-并避免选择和激活要处理的每个工作表和单元格的不良做法:

Sub Copiar()  
Dim range1 As Range, destin as Range  
Set range1 = Range("k56:k58")
Set destin= Sheets("Plan2").Range("r56")  
For Each cell In range1
   If cell.Value = Range("R55").Value Then
      cell.Offset(0, 2).copy destin
      set destin=destin.offset(1,0)    ' Crucial bit here
   End If
Next  
End Sub

I'm assuming you don't want to overwrite Sheets("Plan2").Range("r56") each time you find the value. 我假设您不想每次发现值时都覆盖Sheets("Plan2").Range("r56") If that's the case, this code writes the found value into the same row it is found on the first sheet. 在这种情况下,此代码将找到的值写入在第一张纸上找到的同一行。

This works without copy paste and selecting or activating cells / sheets. 此功能无需复制粘贴以及选择或激活单元格/工作表即可。 Also if you specify your sheet with the source data, like i did, it doesn't even matter which sheet you start the macro from. 另外,如果您像我一样用源数据指定工作表,甚至从哪个工作表开始宏都没有关系。

Sub Copiar()

Dim range1 As Range
Set range1 = Sheets(1).Range("K56:K58")

For Each cell In range1
   If cell.Value = Sheets(1).Range("R55").Value Then
        Sheets("Plan2").Range("R" & cell.Row).Value = cell.Offset(0, 2).Value
   End If
Next

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM