简体   繁体   English

从自定义VBA函数(不是子函数)写入Excel工作表

[英]Writing into Excel worksheet from custom VBA function (not sub)

I would greatly appreciate your assistance in helping me write data from a custom VBA function into an excel worksheet. 非常感谢您的帮助,可以帮助我将自定义VBA函数的数据写入excel工作表。 I have been able to write from a custom VBA subroutine but get an error whilst executing a VBA function. 我已经能够从自定义VBA子例程编写代码,但是在执行VBA函数时遇到错误。 In the sample code, "Sub write 2" and "Sub write 3" work just fine. 在示例代码中,“ Sub write 2”和“ Sub write 3”可以正常工作。 But "Function test 2()" generates "Value!" 但是“功能测试2()”会生成“值!” in its cell and write3 isn't executed. 在其单元格中,未执行write3。

Sub write2(r As Integer, c As Integer, d As Double)
    Dim a, b As Integer
    For a = r To r + 1
        For b = c To c + 1
            Cells(a, b).Value = d
        Next b
    Next a
End Sub

Sub write3()
    Call write2(3, 60, 0.437)
End Sub

Function test2() As Double
    Call write3
    test2 = 1#
End Function

As per Chip Pearson's great website : 根据Chip Pearson的出色网站

A UDF can only return a value to the cell(s) whence it was called -- it must not modify the contents or formatting of any cell and must not modify the operating environment of Excel. UDF只能将值返回到调用它的单元格-不得修改任何单元格的内容或格式,也不得修改Excel的操作环境。 If you attempt to change anything, the function will terminate immediately and return a #VALUE error to the calling cell. 如果您尝试更改任何内容,该函数将立即终止,并向调用单元格返回#VALUE错误。

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

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