Cleaning cells with a VBA function

前端 未结 2 441
一整个雨季
一整个雨季 2021-01-22 03:26

I want to create a VBA function, myFunction(), that writes content in cells and when the calculation is done, it would clear all the data it wrote. (I want to call

相关标签:
2条回答
  • 2021-01-22 03:57

    Instead of UDF you can use events. Please put the below code on any sheet code section.

    limitations of UDF

     Private Sub Worksheet_Change(ByVal Target As Range)
        On Error Resume Next
        Application.EnableEvents = False
    
        If Not Intersect(Target, Range("$A$1:$B$9")) Is Nothing Then
    
            ' your code here
            Range("$A$1:$B$9").Clear
        End If
    
        Application.EnableEvents = True
    
    End Sub
    

    The above code is like a workaround. It will be triggered when values in Range("A1:B9") are changed from excel interface.

    A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. This means that such a function cannot do any of the following:

    • Insert, delete, or format cells on the spreadsheet.
    • Change another cell's value.
    • Move, rename, delete, or add sheets to a workbook.
    • Change any of the environment options, such as calculation mode or screen views.
    • Add names to a workbook.
    • Set properties or execute most methods.

    for more details read the link provided earlier. enter image description here

    0 讨论(0)
  • 2021-01-22 04:00

    Why won't it work when called by myFunction() ?

    A function, called from the Worksheet, cannot manipulate objects on the worksheet, it can only return a value to the cell wherein the function has been called from. I believe this is to prevent circular reference and infinite loops.

    The loophole is that a function called from within a subroutine can manipulate worksheet objects, but that's probably not a good habit to get in to.

    As a best practice, use Subroutines to manipulate objects, and Functions only to return values -- whether to the sheet or to a subroutine.

    How can I solve this ?

    @Santosh's answer, above, should do the trick.

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