hughesdan hughesdan - 1 year ago 131
C# Question

Accessing selected range address and cell values in Excel add in

I'm endeavoring to write an Excel 2010 application add-in using .NET 4 and VS 2010. What's proving difficult is accessing the range of cells selected by the user. The user will select a series of n consecutive cells and then click a button on the ribbon bar. Then after this button is clicked I need to access both the cell addresses for the range and also the cell values. Below is my code. get_Range is the closest method I've been able to find to what I need. However, this method requires the first and last cell address. Is there a similar method to this that will take the user-selected input range as a parameter? Also, after accessing the selected range I need to take the values contained in that range and to write them to a database. I'm envisioning using something like range.SelectedValues that I would cast into a data table. What is the correct way to access the set of selected values?

Thanks in advance for any assistance. I'm lost in the PIA documentation and struggling to accomplish what should be a simple task.

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

namespace ExcelAddIn2
public partial class Ribbon1

private void Ribbon1_Load(object sender, RibbonUIEventArgs e)


private void GetRageValues()

Range range = Globals.ThisAddIn.Application.get_Range("A1", "A3");

//to be replaced with database insert
System.Windows.Forms.MessageBox.Show("You Selected" + range.Address);

private void button1_Click_1(object sender, RibbonControlEventArgs e)



Answer Source

In VBA the object you want is Selection, The type of this object will vary depending on what is selected, if it's a range then it will be of type Range. I'm not sure what the equivalent is in Interop but it should be similar.

(Moved comment to Answer)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download