![](/img/trans.png)
[英]Compile Error: Method 'Range' of object '_Global' failed - Search Copy Paste Macro 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
關鍵字錯誤。 在上面的代碼中,您只需要使用它來分配Worksheet
和Range
對象,而不是整數和字符串。 刪除這些行上的Set
關鍵字。
另外,您在For
循環中缺少End If
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.