Wait For Line 1 To Finish Execution Before Starting Line 2

chalupabatman

Member
Joined
Nov 6, 2014
Messages
8
Programming Experience
Beginner
I am opening an Excel workbook and refreshing a few queries then saving the workbook. My issue is that it is saving the workbook before it is completely refreshed. What can I do in my syntax to ensure that the workbook is completely refreshed before it saves?

C#:
namespace RubarbJones
{
    public partial class Form1 : Form
    {
        
        public BackgroundWorker backgroundWorker1 = new BackgroundWorker();
        public static Excel.Application oXL;
        public static Excel._Workbook oWB;
        public static Excel._Worksheet oWS;
        public static string filename = "R:\\Excel\\Workbooks\\BaseTemplate.xlsx";
        
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        }


        private void btn1_Click()
        {
             backgroundWorker1.RunWorkerAsync();
        }
        
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (oXL == null)
            {
                oXL = new Excel.Application();
                oXL.Visible = true;
                oXL.DisplayAlerts = false;
                oWB = oXL.ActiveWorkbook;
            }
            oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename));
            oWB = oXL.ActiveWorkbook;
            oWS = (Excel._Worksheet)(oWB.ActiveSheet);
            oWB.RefreshAll();
            oWB.SaveAs("C:\\Final\\" + oXL.ActiveWorkbook.Name);
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {


        }        
}
 
Last edited:
Top Bottom