我有一个在VBA中使用Range Subtotal Function的Excel VBA。一切都很好,但我需要在一些列上做的是使用不同的公式替换几列上的小计公式。
我需要这样做的原因是因为在其他列上我需要小计结果才能进行不同的计算。
我尝试使用替换,但我的新配方没有显示。
我想做
Selection.Replace What:="SUBTOTAL(9", Replacement:="RC[-1]/RC[-2]", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
如何获取我的新公式?
答案 0 :(得分:0)
当您使用公式对单元格执行Replace
时,如果结果不是有效的公式,我认为不允许替换。鉴于SUBTOTAL
的格式,您的原始公式将类似于
=SUBTOTAL(9,C100:C150)
并且您的替换将导致
=RC[-1]/RC[-2],C100:C150)
这不是有效的公式
如果我理解正确你想要这样的东西
=SUBTOTAL(9,C100:C150)
成为这个
=RC[-1]/RC[-2]
为此,您可以使用Find
搜索所选单元格以查看公式中是否有“SUBTOTAL(9”)。如果是,则用您想要的公式替换整个公式。以下示例
Dim myRange As Range
Dim searchResult As Range
Set myRange = Selection
Set searchResult = myRange.Find(What:="SUBTOTAL(9", LookIn:=xlFormulas)
Do While Not searchResult Is Nothing
searchResult.Formula = "=RC[-1]/RC[-2]"
Set searchResult = myRange.FindNext(searchResult)
Loop