Can I get an active cell in a selected range in Excel?

I work with VSTO. There is asituation in this, in which, when you click the Excel sheet button, an input window will be displayed, and I will get the selected range. I want to know how to get the selected range from the hac input window with the active cell address of the Excel sheet.

object objInputBox= Excel.Application.InputBox(prompt, field, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, 8);
ExcelXP.Range selectedRange = objInputBox as Excel.Range;

string rangeName = selectedRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing); 

string activeCell =Application.Application.ActiveCell.get_Address(true, true, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);

How can I get the active cell address in rangeName?

Thanks in advance

+3
source share
3 answers

Here you can do it using Application.Intersect. An example is VBA, but it can be easily ported to C #.

Sub TestinRange()
    Dim inputRange As Range
    Set inputRange = Worksheets(1).Range("B1:B5")
    Dim IsActiveCellInInputRange As Range
    Set IsActiveCellInInputRange = Application.Intersect(inputRange, ActiveCell)
    If IsActiveCellInInputRange Is Nothing Then
        Debug.Print "Nope, the ActiveCell is not within the Input Range"
    Else
        Debug.Print "Yep, the ActiveCell is within the Input Range. ActiveCell Address: " & ActiveCell.Address
    End If
End Sub
+3
source

not very effective, but it should work.

private bool IsActiveCellInRange(Range selectedRange)
{
  foreach cell in selectedRange.Cells
    if (cell == activeCell)
      return true;
  }
  return false;
}
+1
source
+1

Source: https://habr.com/ru/post/1763559/


All Articles