SOLVED

Why does copying cells work in a Sub but not in a Function?

Copper Contributor

Hello,

 

I am new to VBA and have come across a problem: why does copying values from one cell to another work in a Sub but not in a Function?

 

I have simplified the problem to this description and sample code below.

 

I want to enter a value in A2 and have it copied to D2

 

Cell B2 says "=AutoCopyCells(A2)"

 

Function AutoCopyCells(iSource as Integer)
    Range("A2").Copy Range("D2")
    AutoCopyCells = True
End Function

 

The code in this function is executed (I have stepped through it many times) but it does not copy what I type into cell A2 into D2

 

I have added a button (positioned vaguely in C2) that calls ButtonClickUpdateCells

 

Sub ButtonClickUpdateCells()
    Range("A2").Copy Range("D2")
End Sub

 

When clicking the button calling the Sub the contents of A2 is copied to D2

 

Effectively the code in the function and Sub is the same (except the function has to return a value). So why does clicking on the button (which calls the Sub) work when the function doesn't? What am I missing?

Many thanks,

Luke Dukie

2 Replies
best response confirmed by Lukie_Dukie (Copper Contributor)
Solution

@Lukie_Dukie I guess that's because a function works inside a cell. Just like you can't put e.g. =SUM(A1:A10) in cell A11 and have the result returned in B11. But, with a SUB you can say "sum  A1:A10 and put the result somewhere else".

@Riny_van_Eekelen- Thank you, it is the first time I have seen that as an explanation of the difference between functions and subs - I must be trying to learn VBA from the wrong resources!

1 best response

Accepted Solutions
best response confirmed by Lukie_Dukie (Copper Contributor)
Solution

@Lukie_Dukie I guess that's because a function works inside a cell. Just like you can't put e.g. =SUM(A1:A10) in cell A11 and have the result returned in B11. But, with a SUB you can say "sum  A1:A10 and put the result somewhere else".

View solution in original post