【问题标题】:excel vba value paste all formulas of type "=X()"excel vba值粘贴“=X()”类型的所有公式
【发布时间】:2015-07-08 19:02:28
【问题描述】:

我有一个数据库应用程序,它通过 UDF 将数据存储在数组公式中。

我想要一个宏,它通过工作表/wbook 并通过用给定单元格中的当前值替换 udf 数组公式来中断所有外部链接。

挑战在于不能单独写入给定数组公式中的单元格。例如,像下面这样的宏将导致整个数组在第一次写入时被破坏。

Public Sub breaklink()
Dim c
For Each c In ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas)
    Debug.Print c.FormulaArray
    If InStr(c.FormulaArray, "MYFORMULA(") Then
        Stop
        c.FormulaArray = c.Value
        'c.Value = c.Value     --THIS THROWS ERROR 1004 (Can't edit part of an array)
        Stop
    End If
Next
End Sub

如果有像c.getArrayFormulaRange 这样的单元格方法,那么我可以使用它来创建一个值数组,然后改写数组公式。

可以想象,我可以遍历相邻单元格以尝试找到每个数组的边界,但这似乎很麻烦(另外,我会更改循环期间循环的范围,这可能会引发问题)。是否有任何方法或对象属性可以帮助我识别给定数组公式所占据的整个范围?

【问题讨论】:

  • c.CurrentArray 将返回FormulaArray 中的Range,如果c 中有一个。您可以使用c.HasArray 检查c 中是否存在数组。如果有,它将返回True
  • 顺便说一句,您应该将c 调暗为Range 以访问适用于它的方法和属性列表。
  • 这是完美的。谢谢!

标签: excel array-formulas vba


【解决方案1】:

按照上面simple MAN的建议,这是我的解决方案:

Public Sub breakLinks(scope As String)
Dim formula_tokens()
Dim c As Range, fa_range As Range
Dim ws As Worksheet
Dim token
formula_tokens = Array("MYFORMULA1(", "MYFORMULA2(", "OTHERFORMULA(", "OTHERFORMULA2(")
If scope = "sheet" Then
    For Each c In ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas)
        For Each token In formula_tokens
            If InStr(UCase(c.FormulaArray), token) Then
                If c.HasArray Then
                    Set fa_range = c.CurrentArray
                    fa_range.FormulaArray = fa_range.Value
                Else
                    c.Formula = c.Value
                End If
            End If
        Next
    Next

ElseIf scope = "wbook" Then
    For Each ws In Worksheets
        For Each c In ws.Cells.SpecialCells(xlCellTypeFormulas)
            For Each token In formula_tokens
                If InStr(UCase(c.FormulaArray), token) Then
                    If c.HasArray Then
                        Set fa_range = c.CurrentArray
                        fa_range.FormulaArray = fa_range.Value
                    Else
                        c.Formula = c.Value
                    End If
                End If
            Next
        Next
    Next

End If

End Sub

【讨论】:

  • 在这一行Dim c, fa_range As Range 上,只有fa_range 将被视为Range。如果你想在同一行声明,你必须这样做:Dim c As Range, fa_range As Range
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多