在Excel的VBA中,我希望创建一个公式,它既接受源单元格的值,也接受格式。
目前我有:
Function formEq(cellRefd As Range) As Variant
'thisBackCol = cellRefd.Interior.Color
'With Application.Caller
' .Interior.Color = thisBackCol
'End With
formEq = cellRefd.Value
End Function`这将返回单元格的当前值。我注释掉的部分在单元格中返回一个#VALUE错误。当未注释时,似乎保存了引用的颜色,但是Application.Caller返回一个2023年错误。这是否意味着这不返回所需的Range对象?
如果是这样的话,如何获得引用函数所使用的单元格的range对象?显然是为了将颜色设置为源值。
发布于 2016-08-10 05:47:20
这里有一种方法展示了如何仍然可以使用ThisCell
Function CopyFormat(rngFrom, rngTo)
rngTo.Interior.Color = rngFrom.Interior.Color
rngTo.Font.Color = rngFrom.Font.Color
End Function
Function formEq(cellRefd As Range) As Variant
cellRefd.Parent.Evaluate "CopyFormat(" & cellRefd.Address() & "," & _
Application.ThisCell.Address() & ")"
formEq = cellRefd.Value
End Function发布于 2016-08-10 05:46:12
这就是我用Tim的magic找到的解决上述问题的方法
Function cq(thisCel As Range, srcCel As Range) As Variant
thisCel.Parent.Evaluate "colorEq(" & srcCel.Address(False, False) _
& "," & thisCel.Address(False, False) & ")"
cq = srcCel.Value
End Function
Sub colorEq(srcCell, destCell)
destCell.Interior.Color = srcCell.Interior.Color
End SubdestCell只是对调用函数的单元格的单元格引用。
可以使用其他格式规则交换或添加interior.color。在这个解决方案中,还需要注意三个要点:
sub中,则会不断重新计算;以及Application.Caller或Application.ThisCell不能集成,因为当它引用自身并返回值时,它会触发无限循环或“循环引用”错误。如果将地址与创建字符串的地址结合在一起,则按照Tim的回答,这是可行的。https://stackoverflow.com/questions/38863510
复制相似问题