繁体   English   中英

Excel:从工作表调用vba函数时将当前单元格作为参数传递

[英]Excel: Passing the current cell as argument when calling vba function from worksheet

我正在尝试制作一个 VBA 函数,它接受一个单元格作为参数,并使用各种 Range.Offset 从那里开始工作。 此函数将在工作表单元格中调用。 为了测试,我使用了这个简单的脚本:

Public Function testPublic(targetCell As Range) As Boolean
   targetCell.Offset(0, 3).Value2 = "Test is successful!"
   testPublic = True
End Function

为了查看是否可以使单元格引用起作用,我传递了简单的引用,例如 C5,但我只得到了 #VALUE! 错误。 不知道这有什么问题。

尝试将 Range 更改为 Variant,仍然无效

您不能使用从工作表中调用为 UDF 的函数来更新工作表中的另一个单元格:该函数只能向包含该函数的单元格返回一个值(数组公式可以返回多个值,但同样只能返回到公式已输入)。

有关更多信息,请参阅: https : //support.microsoft.com/en-us/topic/description-of-limitations-of-custom-functions-in-excel-f2f0ce5d-8ea5-6ce7-fddc-79d36192b7a1

试试下面的调用代码

If testPublic(targetCell:=Range1) Then
  MsgBox "success"
End If

功能代码如下。 根据您的逻辑更改 ByRef 和 ByVal。

Public Function testPublic(ByRef targetCell As Range) As Boolean
   targetCell.Offset(0, 3).Value2 = "Test is successful!"
   testPublic = True
End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM