Search code examples
c#excelvstoadd-in

C# Add-In Excel : ActiveSheet


For my first AddIn Excel, i would like select the sheet active and count columns and row in the sheet.

I've created a button in the custom ribbon.

    private void AddValues_Click(object sender, RibbonControlEventArgs e)
        {  
            int lastRow;
            int lastColonne;

            lastRow = Globals.VATTools.Application.Selection.Rows.Count;
            lastColonne = Globals.VATTools.Application.Selection.Columns.Count;

            System.Windows.Forms.MessageBox.Show("Row : " + lastRow + " " + "Columns : " + lastColonne); 

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlApp.Visible = true;             
            Microsoft.Office.Interop.Excel.Workbook xlWb = xlApp.ActiveWorkbook as Microsoft.Office.Interop.Excel.Workbook;
            Microsoft.Office.Interop.Excel.Worksheet xlSheet = xlWb.ActiveSheet;
            Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range("A19"); 
            range.Value = "hello world!";
        }

My first problem : it returns me 1 column and 1 row. But in my sheet, i've 23 columns and 17 rows. Why doesn't this return the correct number of columns and rows in my sheet ?

The second problem : i've an exception on the ActiveSheet :

Microsoft.Office.Interop.Excel.Worksheet xlSheet = xlWb.ActiveSheet;

The error : System.NullReferenceException: 'Object reference not set to an instance of an object.'

I don't understand why i've this error.

Thanks !


Solution

  • First problem :

    You need to use the UsedRange property from your worksheet object. The selection will only give you informations about the current portion of cells selected.

    Microsoft.Office.Interop.Excel.Range usedRange = xlSheet.UsedRange;
    //To get the number of rows/columns
    int totalRows = usedRange.Rows.Count;
    int totalColumns = usedRange.Columns.Count;
    

    Second problem :

    Since you are programming an addin, you don't need to create a new excelApp. The following code will give you access to your document

    Microsoft.Office.Interop.Excel.Workbook xlWb = Globals.ThisAddin.Application.ActiveDocument.Workbook;