Varriant数组在Excel中删除公式

您好,我最近发现相当快的方式来通过一个变种数组进行循环

With Sht LongY = .Rows.Count Dat = .Formula For r = 5 To 6 'LongY If (Dat(r, 1) = "" Or Dat(r, 4) = "") Then GoTo IgnoRow LongX = .Columns.Count For s = 26 To 27 'LongX If (Dat(2, s) = 0 Or Dat(2, s) = "") Then GoTo IgnoCol 'Or Dat(1, s).EntireColumn.Hidden = True Price = Dat(2, s) Ammount = Dat(r, 4) Base = Dat(r, s) Material = Application.WorksheetFunction.RoundUp((Base * Ammount), 2) 'no .values => text 'MsgBox (Material) 'CPrice = Material * Price 'Cost = Cost + CPrice IgnoCol: Next 'Dat(r, 5) = Cost 'Cost = "" IgnoRow: Next Sht.Formula = Dat End With End Sub 

但我不知道这是如何工作,这给我的麻烦。 我有我的投入(也与公式)的大面积,所以当我循环这个领域时,所有的EXCEL FORMULAS转换为.values,我不知道如何避免这种情况。

谢谢你的任何想法。

删除红鲱鱼,你的原始代码这样做:

 With Table ' Note: Table is a Range Dat = .Value ' Dat is now an array of values, with Table.Rows.Count rows ' and Table.Columns.Count columns. .Value = .Dat ' This copies all the values back into the Table cells, ' replacing any existing formulas with their values. End With 

将Excel范围中的所有值提取到VBA数组中是一种我以前从未见过的技术,但速度非常快,易于阅读代码,所以我将从现在开始使用它。

但是,这种便利是一个成本。 如果您将VBA数组中的所有值传回范围,则会清除所有公式。

如果提取公式而不是值(因此可以安全地复制),则无法访问任何基于公式的单元格的值。 这就是为什么你最近的代码失败。

最简单的解决scheme是提取值和公式,但只复制公式。

 Dim Formulas() As Variant, Values() As Variant With Sht ' Sht is a Range object Values = .Value Formulas = .Formula For r = ... For s = ... price = Values(2, s) Ammount = Values(r, 4) Base = Values(r, s) Material = Round(Base * Ammount + 0.005, 2) ' Round Up Cost = ... Next Formulas(r, 5) = Cost Next .Formula = Formulas End With