自动过滤后取消选择范围

时间:2016-02-26 19:23:19

标签: excel vba deselect

这看起来非常简单和直接,但无论我做多少测试和搜索,我都无法解决。我目前有脚本打开AutoFilter而没有选择任何东西,但我想我可以复制数据并粘贴到新工作表中而不选择数据。但是,在完成操作后,它会显示列A:K为选中状态。我一直无法弄清楚如何在工作表上取消选择这些列,也没有找到如何复制和粘贴,而不首先选择它们。任何指导表示赞赏。感谢。

Sub RunScript()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Sheets("Data")

Sheets.Add.Name = "copy"
Dim galreqws As Worksheet
Set galreqws = ThisWorkbook.Sheets("copy")

Sheets("Data").Select
Range("A:K").AutoFilter

ws1.Range("A1:K1000").Copy Destination:=Sheets("copy").Range("A1:K1000")

galreqws.Delete

'Sheets("Data").Select
Range("A:K").AutoFilter
Range("A:K").Select
Sheets("Buttons").Select

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

2 个答案:

答案 0 :(得分:1)

使用.Select通常是不好的做法,除非您真的打算让用户查看所选范围。据我所知,没有需要.Select的行动。

以下是您可以采取的一些改进代码的建议:

Sub RunScript()

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim wsCurrent As Worksheet
    Set wsCurrent = ActiveSheet

    Dim wsData As Worksheet
    Set wsData = ThisWorkbook.Worksheets("Data")

    Dim wsGalreq As Worksheet
    ' Note that .Add will activate the new sheet so we'll
    ' need to reactivate the worksheet that was previously active
    'Set wsGalreq = Worksheets.Add
    'wsGalreq.Name = "copy"
    Set wsGalreq = Worksheets("copy")

    wsData.Range("A:K").AutoFilter 1, "Supplier A"
    ' Find the used range in columns A to K and copy over starting
    ' at cell A1 of wsGalreq
    Intersect(wsData.UsedRange, wsData.Range("A:K")).Copy Destination:=wsGalreq.Range("A1")

    ' Doubt deleting the new sheet was intentional?
    ' wsGalreq.Delete

    ' Now change the view to the desired worksheet, uncomment one:
    'Worksheets("Buttons").Select
    'wsCurrent.Activate

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub

答案 1 :(得分:0)

从代码中删除以下行。

Range("A:K").Select