运行 时间错误 13 程序模块中的类型不匹配 运行 之前成功

Run time error 13 Type Mismatch in program module which ran successfully earlier

示例数据:

0votes

vbaexcel
answered Sep 3, 2015 at 18:53
0votes
Accepted
  'clickable format
vbaexcel
answered Aug 28, 2015 at 14:18

如果答案未被接受,我想在投票和 url 行之间插入一行,并且 url 立即跟随投票行,目的是最终将 5 行分组为 t运行在单行中放置数据。 我使用的代码如下:

Sub insertrow()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet2")
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step -1
    If (Cells(i, "A").Value) Like "*vote*" And (Cells(i + 1, "A").Value) <> "Accepted" Then
        Cells(i + 1, "A").EntireRow.Insert
    End If
Next i
End Sub

我在下一行收到 运行 时间错误 13 类型不匹配,尽管这个程序 运行 昨天晚上成功地获得了类似的数据。

       ` If (Cells(i, "A").Value) Like "*vote*" And (Cells(i + 1, "A").Value) <> "Accepted" `

非常感谢任何帮助。

使用您提供的数据和代码进行了快速测试,没有任何问题。但是,代码有一个问题:虽然您将特定的 sheet 分配给变量,但您继续使用 ActiveSheet。此 sheet 可能不是您的示例数据的 sheet,并且可能包含导致类型不匹配错误的数据。

在 Excel 中编程 VBA 时,您应该始终准确限定您想要工作的工作sheet。一种方法是使用 With 语句。请注意,在 每个 实例 CellsRangeRowsColumns 之前添加一个点 - 告诉 VBA 你指的是 With-语句的对象。

Sub insertrow()
    With ThisWorkbook.Sheets("Sheet2")
        Dim Last As Long, i As Long
        Last = .Cells(.Rows.Count, "A").End(xlUp).Row
        For i = Last To 1 Step -1
            If (.Cells(i, "A").Value) Like "*vote*" _
            And (.Cells(i + 1, "A").Value) <> "Accepted" Then
                .Cells(i + 1, "A").EntireRow.Insert
            End If
        Next i
    End With
End Sub

或者,如果你更喜欢那个:

Sub insertrow()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet2") 
    
    Dim Last As Long, i As Long
    Last = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    For i = Last To 1 Step -1
        If (ws.Cells(i, "A").Value) Like "*vote*" _
        And (ws.Cells(i + 1, "A").Value) <> "Accepted" Then
            ws.Cells(i + 1, "A").EntireRow.Insert
        End If
    Next i
End Sub

通过使用调试器检查相关数据(在本例中为 2 个单元格的内容),通常可以很容易地发现类型不匹配等错误。