在Excel中设置单元格颜色

huangapple go评论54阅读模式
英文:

Setting a cell color in Excel

问题

I'm trying to set a cell color in excel by a VBA function.

如果我在单元格中调用以下代码,设置=测试(0),则它将单元格设置为绿色,如预期所示。

Sub change_cell_color(c1 As Range, colorval As Long)
    c1.Interior.ColorIndex = colorval
End Sub
Function Test(x As Long)

    With Application.Caller
        .Parent.Evaluate "change_cell_color(" & .Address(False, False) & ", 10)"
        
    End With

End Function

然而,如果我尝试使函数具有参数,以便我可以设置任意颜色,那么该函数将失败。

Function Test(x As Long)

    With Application.Caller
        .Parent.Evaluate "change_cell_color(" & .Address(False, False) & ", x)"
        
    End With

End Function

有人有什么建议吗?

英文:

I'm trying to set a cell color in excel by a VBA function.

If I call the following code in a cell by setting =test(0) then it sets the cell green, as expected.

Sub change_cell_color(c1 As Range, colorval As Long)
    c1.Interior.ColorIndex = colorval
End Sub
Function Test(x As Long)

    With Application.Caller
        .Parent.Evaluate "change_cell_color(" & .Address(False, False) & ", 10)"
        
    End With

End Function

However, if I try to parameterize the function so that I can set an arbitrary color, then the function fails.

Function Test(x As Long)

    With Application.Caller
        .Parent.Evaluate "change_cell_color(" & .Address(False, False) & ", x)"
        
    End With

End Function

Does anyone have any advice?

答案1

得分: 2

你的 x 在引号内表示为文本。

尝试:

Function Test(x As Long)

    With Application.Caller
        .Parent.Evaluate "change_cell_color(" & .Address(False, False) & ", " & x & ")"
    End With

End Function
英文:

Your x is denoted as text inside your quotation marks.

Try:

Function Test(x As Long)

    With Application.Caller
        .Parent.Evaluate "change_cell_color(" & .Address(False, False) & ", " & x & ")"
        
    End With

End Function

huangapple
  • 本文由 发表于 2023年5月10日 19:08:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定