简体   繁体   English

VSTO Excel粘贴失败

[英]VSTO excel paste failed

I am trying to copy from one workbook with 5 sheets. 我正在尝试从5张纸的工作簿中进行复制。 Then paste content from all 5 sheets into a different workbook sheet one. 然后将所有5张纸上的内容粘贴到另一张工作簿纸上。

The first paste is successful, then it try to paste the second sheet it generate error: 第一次粘贴成功,然后尝试粘贴第二个工作表,从而产生错误:

The information cannot be pasted because the copy area and the paste area are not the same size or shape. 由于复制区域和粘贴区域的大小或形状不同,因此无法粘贴信息。 Try one of the following: 请尝试以下方法之一:

  • Click a single cell, and then paste. 单击一个单元格,然后粘贴。
  • Select a rectangle that's the same size and shape, and then paste. 选择具有相同大小和形状的矩形,然后粘贴。

Following is my code: 以下是我的代码:

int rowCount = 0;

app = Globals.ThisAddIn.Application;
sourceBook = app.ActiveWorkbook;

targetBook = app.Workbooks.Add(Type.Missing);
targetSheet = targetBook.Worksheets.Add(Type.Missing);
targetSheet.Name = "Merge Result";


foreach (Excel.Worksheet sheet in sourceBook.Worksheets)
{

    Excel.Range workSheetRange = sheet.UsedRange;
    workSheetRange.Copy(Type.Missing);
    Excel.Range pasteStartCell = (Excel.Range)targetSheet.Cells[rowCount + 1, 1];
    Excel.Range pasteEndCell = (Excel.Range)targetSheet.Cells[rowCount + workSheetRange.Rows.Count, workSheetRange.Columns.Count];
    Excel.Range pasteArea = targetSheet.get_Range(pasteStartCell, pasteEndCell);
    pasteArea.Select();
    targetSheet.Paste(Type.Missing, Type.Missing);
    rowCount = rowCount + workSheetRange.Rows.Count;

}

I have also tried with 我也尝试过

Excel.Range pasteStartCell = (Excel.Range)targetSheet.Cells[rowCount + 1, 1];
pasteStartCell.Select()

then paste, same error message. 然后粘贴,同样的错误信息。

Does anyone know which part I went wrong? 有人知道我哪一部分出了错吗?

您应该避免使用.Select()而是尝试Range.PasteSpecial()

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

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