Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Ok guys, so I've found tons of threads that explain how to fill an Excel range from a sub in VB, but none that explains how to do so from a function.

Suppose the following function (even if what I have to work with is much more complicated...):

VB
Option Base 1
Function fill(v As Range) As Double

    Dim a(5, 1) As Variant

    For i = 1 To 5
        a(i, 1) = i
    Next i

    v.Resize(5, 1).Value = a

    fill=0

End Function


So, this little program takes the range v, and I want to fill it with values from vector a. It doesn't work, it returns only #VALUE.
Someone knows why, and more important how to make it work?

What I want it to do is return 0 in the cell where I call the function, and fill the range I selected. I even tried, to no avail, the following:

VB
Function fill() As Double

    Dim a(5, 1) As Variant

    For i = 1 To 5
        a(i, 1) = i
    Next i

    Range("a1:a20").Resize(5, 1).Value = a
    fill = 0
End Function


So my question is: why can't I change the value of a range inside a function? And how can I make it do so?
Posted
Updated 5-Mar-10 11:06am
v2

So I've been playing around with this for about the last hour and it doesn't seem like you can change cell contents from within a formula.

Personally, I don't understand what you're trying to do with that sample code. Why in the world would you take the user's selected range, and then resize it to only 5 cells?

I wrote the following function within a new module in a new excel workbook.

VB
Function FillIn()
    Range("A1").Value = 1
    FillIn = 1
End Function


This function works perfectly if I call it from a button click, but doesn't work if I type "=FillIn()" within a cell.

I have no idea why, but it seems that if you use a function as a formula, something within the cell that is calling it disallows changing any of the other cells. You can get other cell's values, but if you try to change them, it throws an error.

I think you'll have to figure out another way to do what you're wanting.
 
Share this answer
 
The simplest way is to call the Sub that modifies the datas from the function.

As for why it doesn't work is because it is not meant to modify values
or styles/formatting. The main purpose of the Function is to create custom functions that you can call from Excel.
Like =MySum(A1);
 
Share this answer
 
I wanna thank both of you for your answers. Thanks to you, i've found a way around my problem ^^
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900