0

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

但是,我在下面提到的行的标题中收到错误。什么会导致这种情况?

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
    numRows = Range(selectedRange).Rows.Count '<<<<<<<< Error
    numColumns = Range(selectedRange).Columns.Count

    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
    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
        End If
    Next rowNumber

End Sub
4

2 回答 2

1

尝试:

numRows = selectedRange.Rows.Count '<<<<<<<< Error
numColumns = selectedRange.Columns.Count

可能还有其他错误,我没有测试您的完整代码,但这应该可以解决您遇到的直接错误。

于 2013-06-10T14:20:43.743 回答
0

一些技巧:

  1. 在 sub 的顶部声明所有变量
  2. 为每个变量添加一个新行以使您的代码更具可读性
  3. 每当您使用变量来存储行号时,将其声明为 Long
  4. 如果您事先知道要使用的范围,请将其定义为代码中的范围

这段代码应该做一些接近你想要的事情。试一试,让我知道。如果您在运行宏而不是使用“选择”之前知道要使用的范围,我建议为整个第一张工作表指定确切的范围或“Sheets(1).UsedRange”。

Sub SearchCopyPaste()
    Dim fnd As String
    Dim vCell As Range
    Dim rng As Range
    Dim totalCols As Integer
    Dim rowCounter As Long

    'Set this to a specific range if possible
    Set rng = Selection
    totalCols = rng.Columns.Count

    'Get the data to find from the user
    fnd = InputBox("Input data to find")

    'Loop through all cells in the selected range
    For Each vCell In rng
        'If the data is found copy the data and paste it to Sheet2, move down one row each time
        If InStr(vCell.Value, fnd) > 0 Then
            rowCounter = rowCounter + 1
            Range(Cells(vCell.row, 1), Cells(vCell.row, totalCols)).Copy Destination:=Sheets(2).Cells(rowCounter, 1)
        End If
    Next

    'Copy the column headers onto the second sheet
    Sheets(2).Rows(1).EntireRow.Insert
    rng.Range(Cells(1, 1), Cells(1, totalCols)).Copy Destination:=Sheets(2).Cells(1, 1)
End Sub
于 2013-06-10T15:35:50.170 回答