类型不匹配错误13

时间:2017-02-17 04:56:35

标签: vba ms-office type-mismatch

我试图找到一个会忽略错误13(类型不匹配)的代码。我认为当它到达标题时出现错误,它不是整数,而是文本。此脚本将根据E:E中的数字添加下面的空格,但是当它到达第1行时,它将导致错误13.是否有任何方法可以忽略此错误并继续下一个语句?

Worksheets("PCA Cycle").Activate
Dim r, count As Range
Dim Lastrow2 As Long
Dim temp As Integer
Set r = Range("A:J")
Set count = Range("E:E")
Lastrow2 = Range("E" & Rows.count).End(xlUp).Row
For N = Lastrow2 To 1 Step -1
    temp = Range("E" & N) **HERE'S THE ERROR APPEAR**
    If (temp > 0) Then
        Rows(N + 1 & ":" & N + temp).Insert Shift:=xlDown
    End If
Next N

3 个答案:

答案 0 :(得分:0)

我认为这是VBS for Excel - 如果是这种情况,请尝试使用:

On Error Resume Next 

当遇到错误时,它基本上会恢复执行

这是 NOT 理想的解决方案 - 但它可能会抑制其他所需的错误

<强>更新

更理想的解决方案可能是:

If TypeName(Range("E").Value) = "Error" Then Exit Sub 

答案 1 :(得分:0)

哇,我得到了答案。我使用错误处理程序,它解决了我的问题。无论如何,谢谢你回答我的问题。 :)

Worksheets("PCA Cycle").Activate
Dim r, count As Range
Dim Lastrow2 As Long
Dim temp As Integer
Set r = Range("A:J")
Set count = Range("E:E")
Lastrow2 = Range("E" & Rows.count).End(xlUp).Row
For N = Lastrow2 To 1 Step -1
    On Error GoTo Error_handler:  **ADDED**
    temp = Range("E" & N)
    If (temp > 0) Then
        Rows(N + 1 & ":" & N + temp).Insert Shift:=xlDown
    End If
Next N

Error_handler:已添加

LastRow = Worksheets("PCA Cycle").Range("F2").End(xlDown)(x1up).Row
With Worksheets("PCA Cycle").Range("F2")
    .autofill Destination:=Range("F2:F" & LastRow&)

答案 2 :(得分:0)

不要循环到第1行,在第2行完成循环。

'Very import - forces you to declare all variables first,
'otherwise they're created when first used opening up
'problems with variables spelt differently.
Option Explicit

Sub Test()

    'Each variable must be given a data type
    'otherwise it defaults to Variant.
    Dim r As Range, count As Range
    Dim LastRow2 As Long
    Dim temp As Integer
    Dim N As Long '< You didn't declare this variable.

    With Worksheets("PCA Cycle")

        'I can't see where either of these variables are used.
        Set r = .Range("A:J")
        Set count = .Range("E:E")

        'I prefer to use Cells rather than Range - not sure if there's a performance improvement.
        LastRow2 = .Cells(.Rows.count, 5).End(xlUp).Row

        'Loop from last row to row 2.
        For N = LastRow2 To 2 Step -1
            temp = .Cells(N, 5)
            If temp > 0 Then
                .Range(.Cells(N + 1, 1), .Cells(N + temp, 1)).EntireRow.Insert shift:=xlDown
            End If
        Next N
    End With

End Sub

如果您认为第5栏中的文字可能不在标题中,您可以先检查:
If IsNumeric(temp) Then..... End If