Home » excel » Need guidance with a VBA function to paste values in Excel

Need guidance with a VBA function to paste values in Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m a VBA newbie, but have successfully created a handful of useful Excel Functions. The one I’m working on right now, which seems like it should be simple, is eluding me. I think I’m misunderstanding the syntax, and need some guidance.

Consider the following screen capture; I am attempting to create the function in Column E, which is simply the VALUE from D$n.
enter image description here

So far, this is as far as I’ve gotten:

Function PASTVALUE(q As String)
q.PasteSpecial Paste:=xlPasteValues
End Function

which, if I understand properly, is reading the input value (in my case, the contents of cell D$n) as a String, then pasting it using PasteValues.

Do I need to somehow copy it before I paste it? I thought that the q As String parameter was what brought it into the function.

But then if I’m not copying, is it trying to paste from an empty clipboard…in which case I have no idea what I should be using to accomplish this.

Help!

How to&Answers:

You can just ”transfer” the value(displayed) over like this

Function PASTEVALUE(rng As Range)
    PASTEVALUE = rng.Text
End Function

or use the Evaluate() function to evaluate the formula in that range

 Function PASTEVALUE(rng As Range)
        PASTEVALUE = [rng]
    End Function

Answer:

There are some features of Excel’s object model that you cannot access during a calculation; i.e. during the evaluation of a function. Broadly speaking they are the ones that manipulate the value in cells in some way. If the converse were true, then the calculation process in Excel would break.

Pasting clipboard data into the worksheet falls therefore into the forbidden category.

One solution would be to put your code in a macro; accessible by a button on the worksheet. That is outside the calculation cycle and therefore permissible.