在excel中执行向量添加(n行,1列)超过4000次的最快方法是什么?
我认为UDF会太慢,你会推荐吗?我想要添加具有相同名称,相同尺寸的范围,并在多个工作表中进行本地定义。
编辑:我尝试了UDF,其中5000个太慢了:Function NamedRangeExists(ws As Worksheet, strRangeName As String) As Boolean
Dim rngExists As Range
On Error Resume Next
Set rngExists = ws.Range(strRangeName)
NamedRangeExists = True
If rngExists Is Nothing Then NamedRangeExists = False
On Error GoTo 0
End Function
Function sumName(rangeName As String) As Double
Dim ws As Worksheet
Application.Volatile
sumName = 0
For Each ws In ActiveWorkbook.Worksheets
If NamedRangeExists(ws, rangeName) Then
sumName = sumName + ws.Range(rangeName).Value
End If
Next
End Function
答案 0 :(得分:1)
最快的方法是使用数组公式。最简单的方法可能是UDF 如果您使用超过4000次调用的VBA UDF,您将遇到VBE刷新减速错误:您需要从VBA启动计算。
UDF需要是一个多单元阵列UDF:
选择您希望答案的单元格与指定范围的形状相同
在公式栏中键入UDF公式
按Control-Shift-Enter
这是一些示例代码
Option Explicit
Option Base 1
Sub DoCalc()
Application.Calculation = xlCalculationManual
Application.Calculate
End Sub
Function sumName2(rangeName As String) As Variant
Dim ws As Worksheet
Application.Volatile
Dim vArr As Variant
Dim vSum As Variant
Dim oNM As Name
Dim j As Long
For Each ws In ActiveWorkbook.Worksheets
Set oNM = NamedRange(ws, rangeName)
If Not oNM Is Nothing Then
If Not IsArray(vSum) Then
' create vsum array first time only
vSum = ws.Range(oNM).Value2
Else
' fetch array of values and add to vsum
vArr = ws.Range(oNM).Value2
For j = 1 To UBound(vSum)
vSum(j, 1) = vSum(j, 1) + vArr(j, 1)
Next j
End If
End If
Next
sumName2 = vSum
End Function
Function NamedRange(ws As Worksheet, rangeName As String) As Name
Set NamedRange = Nothing
On Error Resume Next
Set NamedRange = ws.Names(rangeName)
End Function