编译错误:需要对象-搜索复制粘贴宏Excel VBA

编译错误:需要对象-搜索复制粘贴宏Excel VBA,excel,vba,Excel,Vba,我试图在Excel VBA 2007中创建一个宏,该宏在选定字段中搜索,如果它在行中的任何位置找到某个字符串,它会将该行复制并粘贴到另一个工作表中 然而,我得到了一个编译错误:在子级别(第1行)上需要对象。我的代码如下 Sub SearchCopyPaste() ' ' SearchCopyPaste Macro ' Searches for a string. If it finds that string in the line of a document then it copies an

我试图在Excel VBA 2007中创建一个宏,该宏在选定字段中搜索,如果它在行中的任何位置找到某个字符串,它会将该行复制并粘贴到另一个工作表中

然而,我得到了一个编译错误:在子级别(第1行)上需要对象。我的代码如下

Sub SearchCopyPaste()
'
' SearchCopyPaste Macro
' Searches for a string. If it finds that string in the line of a document then it copies and pastes it into a new worksheet.
'
' Keyboard Shortcut: Ctrl+Shift+W
'

    Dim sourceSheet, destinationSheet As Worksheet
    Set sourceSheet = Worksheets(1)               'Define worksheets
    Set destinationSheet = Worksheets(2)

    Dim selectedRange As Range                    'Define source range
    Set selectedRange = Selection

    Dim numRows, numColumns As Integer                            'Determine how many rows and columns are to be searched
    Set numRows = Range(selectedRange).Rows.Count
    Set numColumns = Range(selectedRange).Columns.Count

    Set destinationRowCount = 1                     'Counter to see how many lines have been copied already
                                                    'Used to not overwrite, can be modified to add header,etc

    Dim searchString As String                      'String that will be searched. Will eventually be inputted
    Set searchString = "bccs"                       'Will eventually be put into msgbox

    For rowNumber = 1 To numRows
        If InStr(1, selectedRange.Cells(i, numColumns), searchString) > 0 Then
            selectedRange.Cells(rowNumber, numColumns).Copy Destination:=destinationSheet.Range(Cells(destinationRowCount, numColumns))
            destinationRowCount = destinationRowCount + 1
    Next rowNumber

End Sub

您使用的
Set
关键字错误。在上面的代码中,您只需要使用它来分配
工作表
范围
对象,而不是整数和字符串。删除这些行上的
Set
关键字


另外,在
For
循环中,如果
For
中缺少
End If

谢谢你的提示,但是现在我在numRows行上得到一个错误,说object'\u Global'的方法'Range'失败了。我将Set关键字保留在定义源范围的行上。您应该提出另一个问题,因为这是一个不同的问题。我想说的是,您可能想了解一下Range()的用法。它看起来可疑,但我无法确定。您也可以跳过该变量,直接使用
选择。
而不是创建
范围
对象。除了@Alexandre的答案外,将此行
更改为Set numRows=Range(selectedRange).Rows.Count
为:
numRows=selectedRange.Rows.Count
并相应地更改为下一行。