Range methods copy and asteSpecial from Microsoft.Office.Interop.Excel don't work

牛肉粒 胖胖的 25 Reputation points
2023-06-14T08:36:54.9066667+00:00

Hi

I used Range.Copy() and Range.PasteSpecial to copy some ranges to another new sheet using “XlPasteType.xlPasteAll”,but just pasted as a picture.Using "xlPasteAllUsingSourceTheme" also get the same picture rather than texts or numbers and formulas.Confused@******@...and would be glad if some one can tell me why.^_^

Microsoft 365 and Office Excel For business Windows
Developer technologies C#
{count} votes

Accepted answer
  1. Anonymous
    2023-06-15T01:59:16.0166667+00:00

    Hi @牛肉粒 胖胖的 , Welcome to Microsoft Q&A.

    I tested the code below without issue.

    By passing Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone as the second parameter to the PasteSpecial method, you can ensure that no operation is performed and only the content is pasted

    using Excel = Microsoft.Office.Interop.Excel;
    
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application excel = new Excel.Application();
            Excel.Workbook wb_to_copy = excel.Workbooks.Open(@"path/to/source/workbook.xlsx");
            Excel.Workbook wb_to_paste = excel.Workbooks.Open(@"path/to/destination/workbook.xlsx");
    
            Excel.Worksheet ws_to_copy = (Excel.Worksheet)wb_to_copy.Worksheets.get_Item(1);
            Excel.Worksheet ws_to_paste = (Excel.Worksheet)wb_to_paste.Worksheets.get_Item(1);
    
            int rows1 = ws_to_copy.UsedRange.Cells.Rows.Count;
            int cols1 = ws_to_copy.UsedRange.Cells.Columns.Count;
            Excel.Range rg1 = ws_to_copy.Range[ws_to_copy.Cells[1, 1], ws_to_copy.Cells[rows1, cols1]];
            rg1.Copy();
    
            Excel.Range rg2 = ws_to_paste.Range[ws_to_paste.Cells[1, 1], ws_to_paste.Cells[rows1, cols1]];
            rg2.PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone);
    
            wb_to_paste.Save();
            wb_to_paste.Close();
            wb_to_copy.Close();
            excel.Quit();
        }
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.