简体   繁体   中英

Excel VBA UDF that return value will override itself

Can I write a UDF in Excel VBA where the return value from the function will override the cell value from it is called from?

The function get information with a sql request. In this case it's only master data for example the item description. If the user will use this function in a worksheet in many cells excel will recalculate the cell value every time you change something. This has poor performance and normally it's only necessary to get the information one time and it hasn't to be updated in this case.

I thought to use application.caller.address method to get the address the function was called from but it seems it can't set the cell value for this address within the function. So the return value of the function should override the original formula that run the function.

Is this possible

thanks for your help

No.

As you may have noticed Excel cells have multiple layers.

One is the "value". Another one the formula you can assign.

A funtions returns a value, therefore the return value only accesses this layer. So you cannot return a replacement for the formula cause it is on another layer.

A function differs from a sub in the return value, a sub does not return anything. Due to your behaviour of "one time usage" a sub will fit your need more than a function, because you dont want to return a value but to remove or replace certain content from cell (the formula).

However, this does not mean you cannot do this with a function - but still not with a return value. But you need to rewrite the whole formula on a data refresh if you would use such a function.

You may have missed a point that you make you laugh yourself I guess. Excel has such a thing natively. But it is not a function.

Copy your cells and paste them but use "values only".

Totally has the same effect.

Also in terms of recalculation... why not turn it off? This would you not make to rewrite the function each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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