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 it from a cell with =myFunction()
) To clear the content, I've put this line at the end, to clean up before finishing:
ActiveSheet.Range("$A$1:$B$9").ClearContents
The problem is that is that it doesn't clear anything. However, I noticed that if I put that line above in a subroutine, and then assign that subroutine to a button, the content will be cleared when I click the button.
When I run the code from the window of the program "Microsoft Visual Basic" (with the play button), the code works perfectly (the content gets cleared) but when I call the function from a cell, the cleaning part doesn't work anymore. Here is the code:
Function myFunction()
ActiveSheet.Range("$A$1:$B$9").Clear
End Function
When I click in a cell and type =myFunction()
, the content in the range $A$1:$B$9 is NOT cleared.
However if I create a subroutine (instead of a function), and call it with a button, the content IS cleared.
Why won't it work when called by myFunction() ? How can I solve this ?