【问题标题】:How do I get the source range or cell address of argument of function in VBA?如何在 VBA 中获取函数参数的源范围或单元格地址?
【发布时间】:2016-11-14 19:38:35
【问题描述】:

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

Public Function ItemNumber(AnyValueFromAnyCell) As String
End Sub

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

这个想法是,如果有人使用我的新函数,该函数也会更改源单元格的填充颜色。

我希望这已经足够清楚了。

【问题讨论】:

  • 您将无法使用 UDF 更改源单元格的颜色。
  • 我撤回我的评论 - 我刚刚发现 Tim William's solution 确实 允许 UDF 修改另一个单元格。 (但使用时应自担风险!)

标签: excel vba


【解决方案1】:

我会将 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

【讨论】:

  • 可能包括 value 是 range 的默认值,应该避免作为参数名称。
  • @Sorceri,它为 Value.Address 的第二次返回 "$F$6" 工作......现在它给了我“编译错误,无效使用属性
  • @NamSandStorm 这很可能是因为你没有分配任何东西,我已经更新了答案
  • @Sorceri ...我的错...要爬进去的洞在哪里...我已经为此奋斗了两个小时,似乎无法思考。感谢您的帮助
【解决方案2】:

稍微扩展Sorceri's answer above 以允许从单元格公式或作为代码中的助手使用该函数,并显示主要问题中要求的代码的其他部分:

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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

    • 谢谢斯科特,你有点失去我了。请原谅,我不是一个编码忍者级别的人。最上面的代码去哪儿了?
    • @NamSandStorm - 好吧,我想这不是 100% 清楚你需要这个功能,因为你没有提供。但是假设您想操作函数中的内容(如您所写),我提供了有关如何根据用户选择将参数传递给函数的描述。我上面写的所有内容都将进入一个单独的程序。以 Sub MySub() 为例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    相关资源
    最近更新 更多