如何创build从源单元格中获取值和格式的VBA公式

在Excel的VBA中,我想创build一个既能从源单元格中获取值又能获得格式的公式。

目前我有:

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对象?

如果是这样的话,我如何获得引用该函数的单元格的范围对象? [显然为了将颜色设置为源值]。

下面介绍一下如何使用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 

这是我用Tim William的魔法发现上述问题的解决scheme:

 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 Sub 

destCell只是调用函数的单元的单元引用。

interior.color可以与其他格式规则交换或添加。 在这个解决scheme中要注意三点:

  1. 通过保持公式中的值计算,当destCell引用自身时,将停止循环引用的可能性。 如果放置在sub则不断重新计算; 和
  2. 如果仅在源值更改时更改格式,则格式不是UDF运行的唯一触发器,因此将更改格式;
  3. Application.CallerApplication.ThisCell不能被集成,因为当它引用自身并为其自身返回一个值时,它会触发无限循环或“循环引用”错误。 如果与一个地址合并来创build一个string,那么这个工作虽然按照Tim William的回答。