Excel row select code stops working after 45 cells

时间:2015-11-12 12:13:45

标签: excel-vba search runtime-error row worksheet

I have code that selects specific rows in an Excel 2010 worksheet. I select a cell with a value I'm interested in, run the macro, and any row containing a cell with match value is selected.

The Code:

Sub SelectManyRows()
    Dim CatchPhrase As String
    Dim WholeRange As String
    Dim AnyCell As Object
    Dim RowsToSelect As String

    CatchPhrase = Selection.Value
    'first undo any current highlighting
    Selection.SpecialCells(xlCellTypeLastCell).Select
    WholeRange = "A1:" & ActiveCell.Address
    Range(WholeRange).Select
    On Error Resume Next ' ignore errors
    For Each AnyCell In Selection
        If InStr(UCase$(AnyCell.Text), UCase$(CatchPhrase)) Then
            If RowsToSelect <> "" Then
                RowsToSelect = RowsToSelect & "," ' add separator
            End If
            RowsToSelect = RowsToSelect & Trim$(Str$(AnyCell.Row)) & ":" & Trim$(Str$(AnyCell.Row)) 
        End If
    Next
    On Error GoTo 0 ' clear error 'trap'

    If RowsToSelect <> "" Then 'added by me to catch condition where text not found anywhere which would otherwise through error
    Range(RowsToSelect).Select
    End If
End Sub

The problem: This only works if there are 45 or less cells found with matching values. For example I have 45 cells in one worksheet on various rows with the value "test". I run macro and it selects all rows with cells that have value "test". No problems so far! Now I make a 46th cell with value "test". If I run the macro again it gives this error:

Run-time error '1004': Method "Range" of object '_Global' failed

I click on debug and highlighted in yellow is: Range(RowsToSelect).Select

I'm stumped! Any help much appreciated! :)

1 个答案:

答案 0 :(得分:1)

RowsToSelect是字符串的问题,当你使用Range(RowsToSelect)时,你被限制为256个字符。如果长度为RowsToSelect&gt; 256,你会有这个错误。你可以通过放置if length&gt;来欺骗它。 256然后拆分字符串,但有更好的方法来选择多个范围而不是使用分隔符收集字符串:union函数,例如:

Dim r1, r2, r3 As Range
Set r1 = Range("1:1")
Set r2 = Range("11:11")
Set r3= Union(r1, r2)

如果您将这个想法应用于您的代码:

Dim CatchPhrase As String
Dim WholeRange As String
Dim AnyCell As Object
Dim CatchRow, RowsToSelect As Range

CatchPhrase = Selection.Value
'first undo any current highlighting
Selection.SpecialCells(xlCellTypeLastCell).Select
WholeRange = "A1:" & ActiveCell.Address
Range(WholeRange).Select
On Error Resume Next ' ignore errors
For Each AnyCell In Selection
    If InStr(UCase$(AnyCell.Text), UCase$(CatchPhrase)) Then
        Set CatchRow = Range(Trim$(Str$(AnyCell.Row)) & ":" & Trim$(Str$(AnyCell.Row)))
        If RowsToSelect Is Nothing Then Set RowsToSelect = CatchRow Else Set RowsToSelect = Union(RowsToSelect, CatchRow)
    End If
Next
On Error GoTo 0 ' clear error 'trap'

If Not (RowsToSelect Is Nothing) Then 'added by me to catch condition where text not found anywhere which would otherwise through error
    RowsToSelect.Select
End If