private Microsoft.Office.Tools.Excel.Button jumpButton;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
AddJumpButton();
}
private void AddJumpButton()
{
Microsoft.Office.Tools.Excel.Worksheet worksheet = this.Application.ActiveSheet;
jumpButton = worksheet.Controls.AddButton(50, 50, 100, 30, "jumpButton");
jumpButton.Text = "Jump to Cell";
jumpButton.Click += new EventHandler(JumpButton_Click);
}
private void ThisAddIn_Shutdown(object sender, EventArgs e)
{
}
private void JumpButton_Click(object sender, EventArgs e)
{
JumpToReferencedCell();
}
private void JumpToReferencedCell()
{
Excel.Worksheet activeSheet = this.Application.ActiveSheet;
Excel.Range selectedRange = this.Application.Selection as Excel.Range;
if (selectedRange != null)
{
string formula = selectedRange.Formula.ToString();
var (workbookName, cellAddress) = ExtractReference(formula);
if (!string.IsNullOrEmpty(workbookName) && !string.IsNullOrEmpty(cellAddress))
{
try
{
// Ensure the workbook is open
Excel.Workbook referencedWorkbook = null;
foreach (Excel.Workbook wb in this.Application.Workbooks)
{
if (wb.Name.Equals(workbookName, StringComparison.OrdinalIgnoreCase))
{
referencedWorkbook = wb;
break;
}
}
if (referencedWorkbook == null)
{
System.Windows.Forms.MessageBox.Show($"Workbook '{workbookName}' is not open.");
return;
}
Excel.Range targetRange = referencedWorkbook.Sheets[1].Range[cellAddress]; // Assuming first sheet, modify as needed
targetRange.Worksheet.Activate();
targetRange.Select();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Invalid cell reference: " + ex.Message);
}
}
else
{
System.Windows.Forms.MessageBox.Show("The selected cell does not contain a valid cross-workbook formula.");
}
}
else
{
System.Windows.Forms.MessageBox.Show("No cell is selected.");
}
}
private (string workbookName, string cellAddress) ExtractReference(string formula)
{
// Regular expression to match [WorkbookName]SheetName!CellAddress
var match = System.Text.RegularExpressions.Regex.Match(formula, @"\[(.*?)\].*?!(.*)");
if (match.Success)
{
string workbookName = match.Groups[1].Value;
string cellAddress = match.Groups[2].Value;
return (workbookName, cellAddress);
}
return (null, null);
}
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}