2010-09-07 111 views
3

我在VSTO工作。在這裏有一個asposeation,在按鈕點擊Excel工作表時,它會顯示輸入框,我會得到選定的範圍。我想知道如何從inputbox獲取所選範圍hac Excel工作表的活動單元格地址。獲取Excel中選定範圍內的活動單元格嗎?

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); 

如何獲取rangeName中的活動單元格地址?

在此先感謝

回答

3

的CellInNamedrange功能這裏是你能做到這一點,利用Application.Intersect的方式。示例是VBA,但可以輕鬆移植到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 
1

效率不高,但它應該工作。

private bool IsActiveCellInRange(Range selectedRange) 
{ 
    foreach cell in selectedRange.Cells 
    if (cell == activeCell) 
     return true; 
    } 
    return false; 
} 
相關問題