联合范围选择失败

时间:2018-11-21 07:57:44

标签: excel vba excel-vba

我尝试选择一个变量下的并集范围,但失败。

Sub filter()
    'Clear prev result table
    Worksheets("main").Range("A3").CurrentRegion.Delete

    'Declare variable
    Dim selectedRows As Range
    Set selectedRows = Worksheets("contacts").Range("A1:B1")


    'Get total used range in contacts database
    numRows = Mid(Worksheets("contacts").UsedRange.Address, 9)
    For Each cell In Worksheets("contacts").Range("B1:B" & numRows)
        If cell.Value = Worksheets("main").Range("B1").Value Then
            'If true, push into array called selectedRows
            Set selectedRows = Application.Union(selectedRows, Worksheets("contacts").Range(cell.Address))
        End If
    Next

    selectedRows.Select '<------ fail here
    Copy Worksheets("main").Range("A3")
End Sub

宏失败,并显示错误消息:Select方法或Range类失败。 我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

由于工作表“联系人”未处于活动状态,您收到错误消息。添加此行:

Worksheets("contacts").Activate

赞:

Sub filter()
    'Clear prev result table
    Worksheets("main").Range("A3").CurrentRegion.Delete

    'Declare variable
    Dim selectedRows As Range
    Set selectedRows = Worksheets("contacts").Range("A1:B1")


    'Get total used range in contacts database
    numRows = Mid(Worksheets("contacts").UsedRange.Address, 9)
    For Each cell In Worksheets("contacts").Range("B1:B" & numRows)
        If cell.Value = Worksheets("main").Range("B1").Value Then
            'If true, push into array called selectedRows
            Set selectedRows = Application.Union(selectedRows, Worksheets("contacts").Range(cell.Address))
        End If
    Next

    Worksheets("contacts").Activate

    selectedRows.Select '<------ fail here

    'this line below is incorrect
    'Copy Worksheets("main").Range("A3")
End Sub

我建议您阅读这篇文章:How to avoid using Select in Excel VBA-它可以帮助您改善代码。