VBA:在错误的单元格中显示“NA”

用下面的代码我正在计算RSS。 然而,事实上Y范围实际上并不包含值。 我已经超过了错误(运行时错误'1004'),当没有任何值的时候,显示'on error goto next',但是当在那里它只是'复制'与目的单元格中的前一个值相同的值实际上不会有任何

有没有一种方法来显示“NA”,而不是在由于缺乏Y值而无法计算RSS的目标单元格中​​的先前值?

先谢谢你

Private Sub Regr(strWksData As String, WsTools As Worksheet, strWksFF3 As String, strWksResult As String) Dim NoOfRow As Long Dim i As Integer Dim sData As Worksheet Dim sFF3 As Worksheet Dim sResult As Worksheet Dim rX1 As Range Dim rY1 As Range 'General Set sData = Sheets("Return") Set sFF3 = Sheets("FF-3") Set sResult = Sheets("Result") 'Set X ranges Set rX1 = sFF3.Range("C2:E21") 'Set Y ranges Set rY1 = sData.Range("F2:F21") 'Loop through columns 'Provide statistic On Error GoTo ErrorHandling For i = 0 To 5 vStat1 = Application.WorksheetFunction.LinEst(rY1.Offset(0, i), rX1, True, True) sResult.Range("F2").Offset(0, i).Value = vStat1(5, 2) NoOfRow = rY1.Rows.Count WsTools.Range("B2").Value = NoOfRow Next i ErrorHandling: Resume Next On Error GoTo 0 MsgBox ("RSS Done") End Sub 

由于您直接将结果写入工作表,只要利用Application.LinEst v。Application.WorksheetFunction.LinEst的不同错误报告行为即可。

当您调用完全限定的WorksheetFunction ,调用函数中引发的任何错误都将作为运行时错误引发:

Debug.Print Application.WorksheetFunction.Sum("a", "b") '<--runtime error 1004

当您在Application上使用可扩展接口时,被调用函数中引发的任何错误将返回包装在Variant

Debug.Print Application.Sum("a", "b") '<--Prints Error 2015 (#VALUE!)

如果您需要testing以查看是否有错误,则可以使用IsError函数:

 Dim v As Variant v = Application.Sum("a", "b") Debug.Print IsError(v) '<-- True 

在你的情况下,你可以直接写错误值给单元格:

 For i = 0 To 5 Dim result As Variant result = Application.LinEst(rY1.Offset(0, i), rX1, True, True) 'Don't attempt to use the indexer on an error. If IsError(result) Then sResult.Range("F2").Offset(0, i).Value = result Else sResult.Range("F2").Offset(0, i).Value = result(5, 2) End If Next