VBA - Update Other Cells via User-Defined Function

后端 未结 2 1444
盖世英雄少女心
盖世英雄少女心 2020-11-30 12:10

I have a UDF(User-Defined Function) in VBA that needs to modify cell range on Excel.

Since a UDF cannot do this, I tried using Event calls.

When I raise a

相关标签:
2条回答
  • 2020-11-30 12:33

    If call other function with Application.Evaluate method in your UDF function you can change everything on sheet (Values,Steel,Etc.) because VBA does not know which function is called.

    Example:

    Sub UDFfunction()
      Evaluate "otherfunc(""abc"")"
    End Sub
    
    Public Function otherfunc(ByVal str As String)
      ActiveSheet.Cells(1, 1).Value = str
    End Function
    
    0 讨论(0)
  • 2020-11-30 12:37

    Here is a way you can circumvent the restraint, you must do it indirectly. Method copied from Excel - How to fill cells from User Defined Function?:

    In a standard module:

    Public triggger As Boolean
    Public carryover As Variant
    Function reallysimple(r As Range) As Variant
        triggger = True
        reallysimple = r.Value
        carryover = r.Value / 99
    End Function
    

    In worksheet code:

    Private Sub Worksheet_Calculate()
        If Not triggger Then Exit Sub
        triggger = False
        Range("C1").Value = carryover
    End Sub
    

    This could be expanded for your purposes. Essentially, the UDF updates public variables which are then read from the Worksheet_Calculate event to do... anything you like.

    Another more complicated approach would be to write a vbscript file from your function that will attempt to automate Excel and run it via Shell. However, the method I listed above is much more reliable.

    0 讨论(0)
提交回复
热议问题