我正在研究一个复杂的Excel-VBA项目,发现我的Sub有时会失败,错误代码为1004.我通过代码和输入数据进行了多次实验,最后得出结论,错误是由于公式。
这是一个宏来证明FormulaArray不能设置为任意长度的字符串(虽然公式可以):
Public Sub FormulaArrayLengthTest()
Dim rngTarget As Range: Set rngTarget = ActiveSheet.Range("B1")
Dim i As Long: For i = 0 To 321
Dim strFormula As String: strFormula = "=SUM(A1:A2" & String(i, " ") & ")"
Dim lngLength As Long: lngLength = Len(strFormula)
Dim blnSuccess As Boolean: blnSuccess = True
On Error GoTo ErrorHandler
' rngTarget.Formula = strFormula
rngTarget.CurrentArray.FormulaArray = strFormula ' Note: Cell contains an array formula initially
On Error GoTo 0
Debug.Print "Formula of length " & lngLength & " " & IIf(blnSuccess <> False, "succeeded", "failed")
Next i
Exit Sub
ErrorHandler:
' Err.Number=1004, Err.HelpContext=1001004, Source="Microsoft Office Excel", Description="Failed to set FormulaArray property of Range class"
' Note: If I enter the exact same formula that causes this error into the formula editor on the user interface, then it is accepted
' Test Environment: Windows 7 (6.1.7601), Microsoft Excel 2007 (12.0.6665.5003) SP3 MSO (12.0.6662.5000), VBA Version 1054 Retail 6.5.1054 Forms3: 12.0.6604.1000
' rngTarget.Formula = strFormula ' Succeeds at least until 4321
' rngTarget.CurrentArray.FormulaArray = strFormula ' Succeeds until 241, fails from 242
blnSuccess = False
Resume Next
End Sub
有人遇到同样的问题吗?它是否存在于更高版本的Excel中?你知道一个解决方法吗?
我怀疑早期版本的Excel有一个上限,当UI访问Range对象的最新COM接口时,VBA中的引用指向较旧的。我希望通过将我的Range变量转换为更新版本的接口,可以解决问题。你对此有所了解吗?