Name does not exist in the current context

ansalc 436 Reputation points
2021-09-19T15:56:22.527+00:00

In the code below, the line

XlApp.ScreenUpdating = false;

throws the error: The name XlApp.ScreenUpdating does not exist in the current context

How can I fix it?

I can however refer within the same scope to Workbooks and Worksheets of the Excel App XlApp

If I include the line XlApp.ScreenUpdating = false; inside a method in the same class it works fine. But I need at the top to apply to all methods in the class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;

namespace Sample
{

public class EW: EWrapper
{


    static Microsoft.Office.Interop.Excel.Application XlApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

    XlApp.ScreenUpdating = false; //throws error


    Worksheet Inventory_pos = XlApp.Workbooks["Inventory.xlsm"].Worksheets["pos"]; //no error
  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,640 questions
0 comments No comments
{count} votes

Accepted answer
  1. ansalc 436 Reputation points
    2021-09-19T18:05:14.497+00:00

    Thank you Castorix31!


1 additional answer

Sort by: Most helpful
  1. Castorix31 83,106 Reputation points
    2021-09-19T16:21:26.187+00:00

    You can put it in the Constructor, like :

    public class EW: EWrapper
    {
        public Microsoft.Office.Interop.Excel.Application XlApp = null;
        public EW()
        {
            if (Process.GetProcessesByName("excel").Count() > 0)
            {
                XlApp = Marshal.GetActiveObject("Excel.Application") as Microsoft.Office.Interop.Excel.Application;
                XlApp.ScreenUpdating = false;
            }
        }
    }
    
    0 comments No comments