Excel-vba:使用用户定义的函数(UDF)获取单元格公式中的选定单元格

时间:2018-04-26 13:36:06

标签: excel vba excel-vba user-defined-functions

我尝试了一个明显的代码,但它不起作用。

Function SelectedRange(Optional ShiftRow As Long = 0, Optional ShiftColumn As Long = 0) As Range
    Set SelectedRange = Selection.Offset(ShiftRow, ShiftColumn)
End Function

输出始终是具有公式(或多或少的ShiftRow和ShiftColumn)的单元格的值,即使之后我选择其他单元格并手动重新计算整个工作表。
我做错了什么?

2 个答案:

答案 0 :(得分:1)

您的代码可以在 Sub 中使用,而不是工作表单元格:

Function SelectedRange(Optional ShiftRow As Long = 0, Optional ShiftColumn As Long = 0) As Range
    Set SelectedRange = Selection.Offset(ShiftRow, ShiftColumn)
End Function

Sub MAIN()
    Dim r As Range
    Range("B9").Select
    Set r = SelectedRange(1, 1)
    MsgBox r.Address
End Sub

enter image description here

要在工作表单元格中使用,请传回所选单元格的地址

Function SelectedRange2(Optional ShiftRow As Long = 0, Optional ShiftColumn As Long = 0) As String
    Application.Volatile
    SelectedRange2 = Selection.Offset(ShiftRow, ShiftColumn).Address(0, 0)
End Function

首先单击单元格并触摸 F9 以强制计算:

enter image description here

答案 1 :(得分:0)

根据对问题的评论,@ Gary的学生答案的附录:当您点击工作簿中的其他单元格时,此代码将在公式中找到SelectedRange的任何单元格,并计算这些单元格:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rTMP As Range, sTMP As String
    Set rTMP = Me.Cells.Find("SelectedRange", Me.Cells(1, 1), xlFormulas, xlPart)
    If Not rTMP Is Nothing Then
        sTMP = rTMP.Address
        While Not rTMP Is Nothing
            rTMP.Calculate
            Set rTMP = Me.Cells.FindNext
            If rTMP.Address = sTMP Then Set rTMP = Nothing
        Wend
    End If
End Sub