键入不匹配错误

时间:2015-06-02 19:02:03

标签: excel vba runtime-error worksheet type-mismatch

我有以下代码给出了运行时错误13,在行上键入不匹配"如果ws1.cells(i,13)="是"然后" 该列(列M)包含空白单元格,或者"是"。 我试过重新定义"我"作为字符串,它没有改变任何东西。 目标是每一行都有"是"在M列中,整行被复制到名为"输出"的第二张纸上。 任何有关此错误的帮助都将非常感激,也欢迎其他可能符合我目标的想法。 谢谢!

  Sub Sadface()
  Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Trades")
  Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Output")

  For i = 2 To ws1.Range("M65536").End(xlUp).Row
  If ws1.Cells(i, 13) = "Yes" Then
  ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1)
  End If
  Next i

  End Sub

2 个答案:

答案 0 :(得分:1)

听起来好像您已手动从外部数据中删除了错误。如果将此数据带入工作簿是一项定期重复的操作,您可能希望将其自动化。

Sub Happyface()
    Dim i As Long
    Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Trades")
    Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Output")

    With ws1.Columns(13)
        On Error Resume Next
        .SpecialCells(xlCellTypeConstants, xlErrors).ClearContents
        .SpecialCells(xlCellTypeFormulas, xlErrors).ClearContents
        Err.Clear
        On Error GoTo 0
    End With

    With ws1
        For i = 2 To .Cells(Rows.Count, "M").End(xlUp).Row
            If .Cells(i, 13) = "Yes" Then
                .Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1)
            End If
        Next i
    End With

End Sub

尽管我试图避免使用On Error Resume Next¹,但当你不确定它们是否存在时,这是处理Range.SpecialCells method的最便捷的方法。

¹打破某些东西只是为了看它是否存在的概念对我来说似乎总是错误的。

答案 1 :(得分:-1)

试试这个,希望有所帮助

Sub justforyou()
x = 2
y = 2 'this will start the pasting process in the row 2, if you need to change it, you can change it
Sheets("Output").Select
Do While x <= 65536
    If Sheets("Trades").Cells(x, 13).Value = "Yes" Then
        Sheets("Trades").Rows(x).Copy
        Cells(y, 1).Select
        ActiveSheet.Paste
        y = y + 1
    End If
    x = x + 1
Loop

End Sub

相关问题