如何在VBA中获取函数参数的源范围或单元格地址?

时间:2016-11-14 19:38:35

标签: excel-vba vba excel

对于我的项目,我需要获取用户选择的单元格的单元格地址作为我的函数的参数的源:

Public Function ItemNumber(AnyValueFromAnyCell) As String
End Sub

如果用户在使用该函数时选择单元格F6作为“AnyValueFromAnyCell”的源,我需要其地址来操作该单元格。

这个想法是,如果有人使用我的新功能,该功能也会改变源单元格中的fillcolour。

我希望这很清楚。

3 个答案:

答案 0 :(得分:2)

我会将arg的数据类型声明为Range,然后您可以访问该值和地址

Public Function ItemNumber(val As Range) As String
Dim addressOfCell
Dim valueOfCell
    addressOfCell = val.Address 'address of cell
    valueOfCell = val.Value   'value in the cell
End Function

答案 1 :(得分:1)

扩展一点Sorceri's answer above以允许函数从单元格公式或代码中的帮助程序中使用,并显示主要问题中要求的代码的其他部分: / p>

Public Function ItemNumber(arg As Variant) As String
Dim addressOfCell, valueOfCell
Dim rnSource As Range, rnCaller As Range

 On Error Resume Next

 valueOfCell = arg
 set rnSource = IIf(TypeName(arg) = "Range", arg, Nothing)
 addressOfCell = vbNullString
 If Not (rnSource Is Nothing) Then  addressOfCell = rnSource.Address

 Set rnCaller = Application.Caller
 If Not (rnCaller Is Nothing) then
     ' queue task here to change the interior color of the cell calling the function to be executed, as per the following solution:
     ' Source: https://stackoverflow.com/questions/8520732/i-dont-want-my-excel-add-in-to-return-an-array-instead-i-need-a-udf-to-change/8711582#8711582
 End If
End Function

答案 2 :(得分:0)

Dim sAdd as String, val as Variant

sAdd = Selection.Address
val = Selection.Value

Dim sReturn as String
sReturn = ItemNumber(sAdd, val)

然后向函数添加一个参数以返回接受地址为字符串。

Function ItemNumber(sAddress as String, Value) As String
End Function