簡體   English   中英

編譯錯誤:必需的對象-搜索副本粘貼宏Excel VBA

[英]Compile Error: Object Required - Search Copy Paste Macro 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 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關鍵字錯誤。 在上面的代碼中,您只需要使用它來分配WorksheetRange對象,而不是整數和字符串。 刪除這些行上的Set關鍵字。

另外,您在For循環中缺少End If

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM