View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
Diaren Whan Diaren Whan is offline
external usenet poster
 
Posts: 1
Default Interior.Color from a function yields Error 1004

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