在ActiveCell.Value<>时Do上的VBA类型不匹配错误“”

时间:2016-10-07 14:55:07

标签: excel vba excel-vba

嘿我有代码将行移出到另一张带有单元名称的工作表,一个循环直到它在数据末尾碰到一个空白,这里是代码的摘录;

Range("AF2").Select
Do While ActiveCell.Value <> ""
    strDestinationSheet = ActiveCell.Value
    ActiveCell.Offset(0, -31).Resize(1, ActiveCell.CurrentRegion.Columns.count).Select
    Selection.Copy

    Sheets(strDestinationSheet).Select
    N = Cells(Rows.count, "AF").End(xlUp).Row
    lastRow = N

    Cells(lastRow + 1, 1).Select
    Selection.PasteSpecial xlPasteValues
    Application.CutCopyMode = False

    Sheets(strSourceSheet).Select
    ActiveCell.Offset(0, 31).Select
    ActiveCell.Offset(1, 0).Select
Loop

然而,虽然这部分代码在运行它的最新实例之前工作正常,但现在在第二行上抛出错误Do While ActiveCell.Value&lt;&gt; “”,说类型不匹配。我不确定有什么改变可以阻止这种突然的工作,任何想法?非常感谢。

1 个答案:

答案 0 :(得分:4)

我个人不喜欢Do Loops迭代一组单元格。我更喜欢For Each循环。

同样如@bruceWayne所述,避免使用Select as会减慢代码速度。

正确的缩进使代码更易于阅读并避免出现简单错误。

Dim cel As Range
With Sheets(strSourceSheet)
    For Each cel In .Range("AF2", .Range("AF2").End(xlDown))
        If Not IsError(cel) Then
            strDestinationSheet = cel.Value
            cel.Offset(0, -31).Resize(1, cel.CurrentRegion.Columns.Count).Copy
            N = Sheets(strDestinationSheet).Cells(Sheets(strDestinationSheet).Rows.Count, "AF").End(xlUp).Row
            Sheets(strDestinationSheet).Cells(N + 1, 1).PasteSpecial xlPasteValues
        End If
    Next cel
End With
相关问题