Need guidance with a VBA function to paste values in Excel

你说的曾经没有我的故事 提交于 2020-01-16 01:00:28

问题


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.

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!


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/17552220/need-guidance-with-a-vba-function-to-paste-values-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!