在公式中使用几个命名范围的Excel VBA

我试图在VBA中使用一个命名范围在一个公式,但它似乎需要很长时间来计算Excel。 命名范围每个都有近70k的数​​据(全部具有相同的行数)。 以下是代码示例:

Dim i, erow, ecol As Long erow = Sheets("Sheet1").Range("A11").End(xlDown).Row ecol = Sheets("Sheet1").Range("A11").End(xlToRight).Column Sheets("Sheet1").Range(Cells(12, ecol + 2), Cells(erow, ecol + 2)).Formula = "=(0.03 - Ith_LT) * (a_LI_LT * 0.03 ^ 2 + b_LI_LT * 0.03 + c_LI_LT) 

Ith_LT,a_LI_LT,b_LI_LT,c_LI_LT是命名的范围。

我试图加速通过首先存储命名的范围内存然后调用它,但无济于事。 以下是我的代码。

 Dim i, erow, ecol As Long Dim Ith, a, b, c As Variant erow = Sheets("Sheet1").Range("A11").End(xlDown).Row ecol = Sheets("Sheet1").Range("A11").End(xlToRight).Column Ith = Range("Ith_LT") a = Range("a_LI_LT") b = Range("b_LI_LT") c = Range("c_LI_LT") Sheets("Sheet1").Range(Cells(12, ecol + 2), Cells(erow, ecol + 2)).Value = (0.03 - Ith) * (a * 0.03 ^ 2 + b * 0.03 + c) 

当我运行这个时,popup一个types不匹配的错误。 有什么办法可以做这个工作吗? 或者有无论如何使这个代码运行更快? 谢谢。

@Zabjaku根据你的评论,我假设所有的范围是单列,最终的输出是作为公式的结果填充,那么你可以使用这个。

这将填充您的输出列,如果命名的范围发生变化,您不必更改公式。

 Sheets("Sheet1").Range(Cells(12, ecol + 2), Cells(erow, ecol + 2)).Value = "=(0.03-" & Replace(Range("Ith_LT").Cells(1, 1).Address, "$", "") & ")*(" & Replace(Range("a_LI_LT").Cells(1, 1).Address, "$", "") & "*0.03^2+" & Replace(Range("b_LI_LT").Cells(1, 1).Address, "$", "") & "*0.03+" & Replace(Range("c_LI_LT").Cells(1, 1).Address, "$", "") & ")" 

在你的variables声明中,你只定义了给定types的最后一个varibale:

 Dim i, erow, ecol As Long Dim Ith, a, b, c As Variant 

对于第二行,应该使用types范围而不是变体

 Dim Ith as range, a as range, b as range, c as range 

之后你使用这条线来使用命名的范围

 Set Ith = Range("Ith_LT")