如果字符串存在,则复制并粘贴行到新工作表;对象定义错误

时间:2018-05-04 19:37:33

标签: excel vba excel-vba

所以我正在尝试构建代码,如果存在这个字符串,那么我想复制活动单元格的整行并将其粘贴到新工作簿上。

这就是我试图过滤的类似于:

的列

cells with 0 - multiple entries

我一直收到一个对象定义的错误,我不确定如何解决。这是我正在使用的代码

Sub moveData(ByVal i As Long, ByVal j As Long, ByVal k As Long, ByVal row_sum As Double)

Worksheets("HHP").Range("BN").Select
' Change A2 to whatever cell you want the data to be copied to
Worksheets("FastTrackTool").Range("BN").Select

For i = 16 To row_sum
    Do Until IsEmpty(ActiveCell)
        If ActiveCell = "D0Y" Or "D0Z" Or "D1B" Or "D1C" Or "D1D" Or "D0M" Then
            MsgBox (ActiveCell)
            ActiveCell.EntireRow.Copy
            Worksheets("HHP").Select
        With Selection
            .PasteSpecial Paste:=xlPasteValues
        End With
        ActiveCell.Offset(1, 0).Select
        Worksheets("FastTrackTool").Select
    End If
    ActiveCell.Offset(1, 0).Select
Loop
Application.CutCopyMode = False
Next

End Sub

1 个答案:

答案 0 :(得分:0)

我可以在您的代码中看到两个直接问题。第一个问题是你的IF声明。

If ActiveCell = "D0Y" Or "D0Z" Or "D1B" Or "D1C" Or "D1D" Or "D0M" Then

OR不能像这样工作 - 你需要一个条件来检查每个OR,它需要评估为True或False。我在下面的代码中解决了这个问题,但there is an even better, much more concise way to do it with a Select Case statement

If ActiveCell.Value = "D0Y" Or ActiveCell.Value = "D0Z" Or ActiveCell.Value = "D1B" Or ActiveCell.Value = "D1C" Or ActiveCell.Value = "D1D" Or ActiveCell.Value = "D0M" Then

另一个问题是你试图比较Jacob H提到的Range对象。如果您想比较该单元格的,请使用.Value属性/成员(术语?)来访问它。这个错误有两个例子,我也在下面的代码中修复过。

注意:一个实例可能实际上不是一个错误 - 我将MsgBox(ActiveCell)更改为MsgBox(ActiveCell.Value)。但是,您可能希望它弹出地址(ActiveCell.Address)或其他一些属性。

您的代码,带有我的修订版:

Sub moveData(ByVal i As Long, ByVal j As Long, ByVal k As Long, ByVal row_sum As Double)

Worksheets("HHP").Range("BN").Select
' Change A2 to whatever cell you want the data to be copied to
Worksheets("FastTrackTool").Range("BN").Select

For i = 16 To row_sum
    Do Until IsEmpty(ActiveCell)

        If ActiveCell.Value = "D0Y" Or ActiveCell.Value = "D0Z" Or ActiveCell.Value = "D1B" Or ActiveCell.Value = "D1C" Or ActiveCell.Value = "D1D" Or ActiveCell.Value = "D0M" Then
            MsgBox (ActiveCell.Value)
            ActiveCell.EntireRow.Copy
            Worksheets("HHP").Select
        With Selection
            .PasteSpecial Paste:=xlPasteValues
        End With
        ActiveCell.Offset(1, 0).Select
        Worksheets("FastTrackTool").Select
    End If
    ActiveCell.Offset(1, 0).Select
Loop
Application.CutCopyMode = False
Next

End Sub

我没有测试过这段代码,但这些问题突然出现在我面前。如果这样可以解决您的错误,请告诉我。

干杯,祝你好运!