Click here to Skip to main content
15,438,113 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Thanks to @0x01AA @Graeme_Grant for the code

I need a bit of help in optimizing it as it is taking 90 minutes to complete the execution and I'm also not getting desired output where it is removing the column names while checking cell by cell if it is mismatched in destination and also not going through a condition(!src/dst.has formula) as it is pasting data un evenly

With below-mentioned requirements


1. The Whole workbook needs to be copy pasted dynamically without passing sheet names hard coded
2. if Columns are not matching at the destination then ignore and go to next (only copy paste all columns from source).
3. Cells only without formulas needed to be copy pasted from source to
destination.

What I have tried:

using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using _Excel = Microsoft.Office.Interop.Excel;

namespace Excel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            foreach (System.Diagnostics.Process clsProcess in Process.GetProcesses()) // this statement will find instance of the excel file and the instance of excel file
            {
                if (clsProcess.ProcessName.Equals("EXCEL"))
                {
                    clsProcess.Kill();
                    break;
                }
            }
            InitializeComponent();
        }
        //To get SheetNames
        public static List<string> GetAllSheetName(string fileName)
        {
            _Excel.Application xlApp = new _Excel.Application();
            Workbook xlWb = xlApp.Workbooks.Open(fileName); 
            var sheetNames = new List<string>(); 
            foreach (Worksheet xlWs in xlWb.Worksheets)
            {
                sheetNames.Add(xlWs.Name);
            }
            releaseObject(xlApp);
            return sheetNames;
        }
        private void button3_Click(object sender, EventArgs e)
        {
            string safeExcelFilePath = @"[directory of the excel workbooks]";
            string excelFile1 = Path.Combine(safeExcelFilePath, textBox1.Text);
            string excelFile2 = Path.Combine(safeExcelFilePath, textBox2.Text);
            _Application _excel = new _Excel.Application();
            _excel.DisplayAlerts = false;
            Workbook workbook1 = _excel.Workbooks.Open(excelFile1);
            Workbook workbook2 = _excel.Workbooks.Open(excelFile2);
            List<String> wb1 = GetAllSheetName(excelFile1);
            List<String> wb2 = GetAllSheetName(excelFile2);
            //Compare both sheetNames
            Worksheet worksheet1 = null;
            Worksheet worksheet2 = null;
            //Range ranges = ;
            //for (int i = 1; i <= 6; i++)
            //{
                foreach (string sheet1 in wb1)
                {
                    worksheet1 = workbook1.Worksheets[sheet1.ToString()];
                    foreach (string sheet2 in wb2)
                    {
                        worksheet2 = workbook2.Worksheets[sheet2.ToString()];
                        if (sheet1.Equals(sheet2) )
                        {
                            for (int rowIX = 1; rowIX <= 250; rowIX++)
                          
                            
                            {
                                for (int colIX = 1; colIX <= 30; colIX++)
                               
                               
                                {
                                    Range src = worksheet1.Cells[rowIX, colIX];
                                    if (!src.HasFormula && src!=null  )
                                    {

                                        Range dst = worksheet2.Cells[rowIX, colIX];
                                        if (!dst.HasFormula)
                                        {

                                            dst.Value = src.Value;

                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            //}
            workbook2.SaveAs(Filename: excelFile2, AccessMode: XlSaveAsAccessMode.xlNoChange);
            workbook2.Close();
            workbook1.Close();
            releaseObject(_excel);
            //_excel.Quit();
        }
        
       
}
Posted
Updated 27-Jul-22 23:52pm
v4

To be honest, there is no point at all in trying to "optimise" code that doesn't do what you need it to: it may be the fault that causes it to run slowly, or it will need reoptimizing after the fault is fixed.

So start by making it do what you need it to, which we can't do as we have no access to your data, and that is probably very relevant to the problem.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!

When you have the code fully working, start by using the Stopwatch Class (System.Diagnostics) | Microsoft Docs[^] to find where the code is slow and get an accurate baseline set of measurements to show how much of an improvement (or otherwise) changes make.
Focus on the slow bits, as they will give the biggest "rewards".
 
Share this answer
 
Comments
Randomuser787 27-Jul-22 11:54am     CRLF
Thanks for your suggestion sir!! Have tried debugging all as I have given used range the if loop on row and col goes to 2000 on all 6 sheets unnecessarily if there is no data also. and now just for testing hard coded numbers of columns and rows and if columns are mismatching it is just removing the columns header name and not going to next on the destination but instead starting at first on the next row. these are what I noticed on debugging. Actually the task was to copy and paste cells/sheets from the source excel workbook to destination workbook which doesn't have formulas ignore if columns are missing in destination
Quote:
How to optimize this and correct my code! !

First make it correct, then make ot fast.
We have no real clue of what can be wrong in this code.

What I do for faster macros:
VB
Sub Mac_Deb()
    ' Get App Status
    calcState = Application.Calculation
    eventsState = Application.EnableEvents

    'turn off some Excel functionality so your code runs faster
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
   
    ' Do Stuff Here

    'after your code runs, restore state; put this at the end of your code
    Application.Calculation = calcState
    Application.EnableEvents = eventsState

End Sub

Translation to C# should not be too complicated.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900