excel vba compare & copy worksheets from 2 excel files

非 Y 不嫁゛ 提交于 2019-12-08 14:24:06

问题


i've workbook 1 with 100 worksheets.
i've workbook 2 with 200 worksheets.

i need to perform 2 tasks:

  • For those existing worksheets(same worksheet name in both books), i want to delete book 1 worksheet content (column A-Z) and copy content (column A-Z) from book 2 to book 1.

  • For those missing worksheets in workbook 1, i want to copy the entire worksheet from book 2 to book 1.

pls advise if there are any existing online vba, thanks.


回答1:


First of all you need to loop through all your worksheets for both, open the 2 workbooks, and loop through both, then you can select them, compare if their name exists in the other worksheet, if not, you add it, otherwise, you copy the content from one to the other one and at the end you should save them. Solution in C#, see link for solution in VB.NET, something similiar is to apply for VBA.

Excel.Workbook workbook;
workbook = xlsApp.Workbooks.Open("first file", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Workbook workbook2;
workbook2 = xlsApp.Workbooks.Open("second file", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
foreach (Excel.Worksheet sheet in workbook.Sheets)
{
    workbook.Activate();
    sheet.Activate();
    foreach (Excel.Worksheet sheet2 in workbook2.Sheets)
    {
         workbook2.Activate();
         sheet2.Activate();
         if(sheet2.Name.Equals(sheet.Name))
         {
             sheet.Range("A1:Z65535").Copy(Missing.Value);
             sheet2.Range(cellmapp).PasteSpecial(); // where cellmap = A1:Z65535
         }
         else
         {
             Excel.Worksheet newWorksheet;
             newWorksheet = (Excel.Worksheet)this.Application.Worksheets.Add();
             sheet.Range("A1:Z65535").Copy(Missing.Value);
             newWorksheet.Range(cellmapp).PasteSpecial(); // where cellmap = A1:Z65535
             snewWorksheet.Range("A1:Z65535").Copy(Missing.Value);
             newWorksheet.Columns.AutoFit();
         }
    }
}

http://www.developerfusion.com/tools/convert/csharp-to-vb/?batchId=36c4611b-294a-4f87-a762-1016ad46d508



来源:https://stackoverflow.com/questions/17719498/excel-vba-compare-copy-worksheets-from-2-excel-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!