Excel 宏 VBA - 如何插入复制的单元格而不是粘贴

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25824116/
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-12 04:31:45  来源:igfitidea点击:

Excel Macro VBA - How to insert copied cells instead of paste

excelvbaexcel-vba

提问by batchnewbie

I have a macro running with the following code to copy data from one Excel file into another Excel file. Currently it is copying and pasting the data into the second Excel file. This means it overwrites any data that is in the second Excel file.

我有一个运行以下代码的宏,用于将数据从一个 Excel 文件复制到另一个 Excel 文件中。目前它正在将数据复制并粘贴到第二个 Excel 文件中。这意味着它会覆盖第二个 Excel 文件中的任何数据。

I would like it to insert the copied cells rather than paste over the data already in the workbook. How should I edit line 27 to make this work?

我希望它插入复制的单元格而不是粘贴工作簿中已有的数据。我应该如何编辑第 27 行来完成这项工作?

I think I need to use the following code but I'm not sure how to apply it to my original code.

我想我需要使用以下代码,但我不确定如何将其应用于我的原始代码。

InsertCopiedCells

Here is the original code that is pasting the data.

这是粘贴数据的原始代码。

Const strFile As String = "E:\My Documents\file2\file\MonthlyReports\Data\file1.xlsx" 
'Add the file location

    Dim wbCopyTo    As Workbook
    Dim wsCopyTo    As Worksheet
    Dim wbCopyFrom  As Workbook
    Dim wsCopyFrom  As Worksheet

    Set wbCopyTo = ActiveWorkbook
    Set wsCopyTo = ActiveSheet

    '-------------------------------------------------------------
    'Open file with data to be copied

    Set wbCopyFrom = Workbooks.Open(strFile)
    Set wsCopyFrom = wbCopyFrom.Worksheets(1)

    '--------------------------------------------------------------
    'Copy Range

    wsCopyFrom.Range("A2:AA5000").Copy
    wsCopyTo.Range("A2").PasteSpecial Paste:=xlPasteValues, _
            Operation:=xlNone, SkipBlanks:=False, Transpose:=False

回答by shahkalpesh

Replace

代替

wsCopyTo.Range("A2").PasteSpecial Paste:=xlPasteValues, _
            Operation:=xlNone, SkipBlanks:=False, Transpose:=False

to

wsCopyTo.Range("A2").Insert xlShiftDown