Interior.Color from a function yields Error 1004

D

Diaren Whan

In Excel 2007 I am trying to change the Fill color of a cell from a macro. I
am fairly adept with excel macros. So here is the problem with a simple
example.

Sub FormatResult()
Range("A1").Interior.Color = 255 '*** This Works
End Sub

Add a formula to a cell e.g. =FormatResultByRange(A1)
Function FormatResultByRange(r as Range)
r.Interior.Color = 255 '*** Error 1004
End function

alternatively...
Function FormatResultByRange(r as Range)
' r is ignored and not used
Range("A1").Interior.Color = 255 '*** Error 1004
End function

It doesn't seem to work when executed via a formula.

Code In Context:
I know the follwoing example can be achieved using coditional formatting,
but the real code is actually very complex involving 3d math etc. But what is
below illustrates the problem in context.

n.b. cell formula: = FormatAge()
Function FormatAge()
Dim r as Range
Dim age as Integer
Dim fmtcolor as Variant
Set r = Application.Caller
age = r.Value
if(age<16) then
fmtcolor = &H0000FF
else
if(age<18) then
fmtcolor=&HFF8000
else
fmtcolor=&H00FF00
end if
end if
r.Interior.Color = fmtColor '*** Error 1004
End Function
 
J

JP

You've discovered one of the limitations of functions -- a UDF cannot
do anything to the worksheet.

A function can return a value as the result of a calculation, but you
can never do something that would affect the worksheet such as
changing colors,

Check out this KB: http://support.microsoft.com/kb/170787


HTH,
JP
 
D

Diaren Whan

If that is the case, then I find it strange that the following works from a
UDF:

Range("A1").Font.Color = 255

Nevertheless the above is what has been used until a better solution comes up.

Thanks for your time.
 
J

JP

I tried it but it didn't work on my machine no matter what combination
I used.

r.Interior.Color
r.Font.Color
Range("A1").Interior.Color
Range("A1").Font.Color


Can you explain what you are trying to do with the formula? Maybe
someone could be of further assistance.

HTH,
JP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top