VBA:显示" NA"在单元格中出错

时间:2017-03-21 18:23:37

标签: excel vba excel-vba

使用以下代码我正在计算RSS。然而,确实Y范围实际上不包含值。我已经超过了错误(运行时错误' 1004'),如果没有任何值,并且出现错误,则显示错误转到下一个'但它只是复制'与目标单元格中​​的前一个值相同的值,而实际上并不存在任何值。

有没有办法显示" 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

1 个答案:

答案 0 :(得分:1)

由于您将结果直接写入工作表,因此只需利用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!)

如果您需要测试是否有错误,可以使用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