【问题标题】:How to add modification to all formulas from a selected range in excel如何在excel中对选定范围内的所有公式添加修改
【发布时间】:2021-07-01 20:08:40
【问题描述】:

我想使用附加的 if 语句来限制选定单元格区域中的所有公式。

使用VBA是否可行?

假设: 单元格 A1 包含 =sum(B1;C1) 但它可以是所选单元格包含的任何公式 应用宏更新公式后将是 =if(D100>0;sum(B1;C1);0)

=if(D100>0;单元格中的任何公式 ;0)

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您可以使用如下代码实现此目的:

    Sub ModifyFormulas()
        Dim cl As Range, formulas_cells As Range
        Const template = "=if(D100>0,#,0)"  '# will be replaced by old formula without '='
        On Error Resume Next    ' handle an error if there are no formulas in the range
        Set formulas_cells = Range("A1:A10").SpecialCells(xlCellTypeFormulas)
        On Error GoTo 0
        If Not formulas_cells Is Nothing Then
            For Each cl In formulas_cells
                cl.Formula = Replace(template, "#", Mid(cl.Formula, 2))
            Next
        End If
    End Sub
    

    【讨论】:

    • 这个作品超级酷。谢谢你。但是我怎样才能只对带有公式的单元格而不是包含值的单元格或空白单元格执行它?
    • 看来我已经想通了。将 [ For Each cl In Range("A1:A10") ] 行更改为 [ Each cl In Cells.SpecialCells(xlCellTypeFormulas) ] 解决了问题。 :)
    • @Tom0101 已更新。还添加了错误处理程序
    【解决方案2】:

    没有vba,我使用如下方法:

    1. 用“xyxy”编辑/替换“=” - 这会停止 excel 重新计算

    2. 然后用“if(D100>0;sum”编辑/替换“sum”

    3. 然后用“);0)”编辑/替换“)”

    4. 最后将“xyxy”替换为“=”

    然后一切正常,当我不得不更改一些计算时,经常用我的工作表来做这件事......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      相关资源
      最近更新 更多