vba 宏将数据从一张纸复制到另一张纸,前提是尚未存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12223073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:55:38  来源:igfitidea点击:

Macro to copy data from one sheet to another, only if not already present

excelvbaexcel-vba

提问by user1639703

I am struggling with this macro. I have two sheets; One with a large set of data that is updated by a macro with respect to multiple dates.

我正在努力解决这个宏。我有两张床单;一个包含大量数据的数据集,由宏针对多个日期进行更新。

I want to copy the data from that sheet ("rawdata1") to another sheet ("sheet1"), but only if the data isn't already present (don't want multiple entries of the same data on "sheet1"). I have no problem copying the data to the other sheet but how do you avoid duplicate entries when the macro is run multiple times?

我想将数据从该工作表(“rawdata1”)复制到另一张工作表(“sheet1”),但前提是数据尚不存在(不希望在“sheet1”上有多个相同数据条目)。我将数据复制到另一个工作表没有问题,但是当宏多次运行时如何避免重复条目?

The code I have so far:

我到目前为止的代码:

Sub CopyData()
'Copy data if not present in other sheet
'???

Sheets("rawdata1").Select
Range("A4:AC10000").Select
Range("A4:AC10000").Copy

Sheets("Sheet1").Select
  ' Find the last row of data
  FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
  ActiveSheet.Paste
  Sheets("Sheet1").Select

Thanks for the help!

谢谢您的帮助!

回答by Tim Williams

Your code can be simplified to:

您的代码可以简化为:

Sheets("rawdata1").Range("A4:AC10000").Copy _
      Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1,0)    
Sheets("Sheet1").Select

As for preventing multiple copies of the same line, if you're in Excel 2007+ then you can use RemoveDuplicates after running the copy: this will reduce the range down to unique rows only. Note: you need to adjust the Columnsparameter to include all relevant column numbers.

至于防止同一行的多个副本,如果您使用的是 Excel 2007+,那么您可以在运行副本后使用 RemoveDuplicates:这会将范围缩小到仅唯一行。注意:您需要调整Columns参数以包含所有相关的列号。

ActiveSheet.UsedRange("$A:$E").RemoveDuplicates _
    Columns:=Array(1, 2, 3, 4, 5), Header:=xlYes 'or xlNo, depending on your data