I am very new to VBA. I want to use vba function to achieve the following:
Sheet1:
Year ----- | - 1 - | - 2 - | - 3 - |
Revenue | $10 | $20 | $30 |
Sheet2:
Year ------| 1 | 2 | 3 |
Revenue | X | Y | Z |
Revenue is a named cell. Using excel function, I can link the revenue of each year to cell X through Z on Sheet 2 or any other worksheet using:
=Offset(Revenue,0,column()-1)
I want to achieve the same thing in VBA Function to shorten the formula to something like Obtain(Revenue). Here is what I have come up with so far:
In VBA:
Function Obtain(Account As Range)
Dim i As Integer
i = ActiveCell.Column - Account.Column
Obtain = Account.Offset(0, i).Value
End Function
And in cell X:
=Obtain(Revenue)
While it does (almost) the same thing as the formula version, I run into problem when I copy the formula from X and paste it to Y and Z across the same row. Instead of getting $10, $20, $30, I get $10, $10, $10 because the Active.Cell is "stuck" to X, unless I move the mouse cursor and press Enter to refresh the ActiveCell for each function in Y and Z. What can I do to this Obtain VBA function so that when I copy and paste Obtain(Revenue) to other cells, excel knows which year of revenue I am referring to?
Thanks!