Home » excel » excel – Macro Running from formula doesn't copy/paste, but running through vbe it works fine

excel – Macro Running from formula doesn't copy/paste, but running through vbe it works fine

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a cell in A1 with HYPERLINK formula calling an UDF:

=HYPERLINK("#funcCopy()";"macro")

The UDF simply copy and paste 3 cells into another location:

Public Function funcCopy()
    Set funcCopy = Selection

    Dim plan As Worksheet
    Dim copyrow As Range

    Set plan = ThisWorkbook.Sheets("Plan1")

    Set copyrow = plan.Range("A3:E3")
    copyrow.Copy plan.Range("A5")
    MsgBox "I'm actually working!"
End Function

But when I click on the hyperlink, it just doesn’t copy/paste. I add the MsgBox to verify if the function is running (and it is!).
Running through VBE works fine.

I’m out of solution to this. Is there something I can do?

How to&Answers:

Copy doesn’t seem to work, but a direct value transfer does, if that suits your requirements.

Public Function funcCopy() As Range
    Set funcCopy = Selection

    Dim plan As Worksheet
    Dim copyrow As Range

    Set plan = ThisWorkbook.Sheets("Plan1")

    Set copyrow = plan.Range("A3:E3")   
    plan.Range("A5:E5").Value = copyrow.Value

    MsgBox "I'm actually working!"
End Function

enter image description here

(Edited to make the return type explicit, credit goes to @Mathieu Guindon for pointing that out.)