【问题标题】:Select range in another file after opening it打开后在另一个文件中选择范围
【发布时间】:2022-08-18 15:45:31
【问题描述】:

你能帮我解决以下问题吗? 我有一个代码可以在特定位置打开一个 excel 文件并在其中进行过滤,但在此之后我无法选择我需要的范围:

Private Sub CommandButton1_Click()

\'dim Wb as string
\'dim Newdata as string

    Newdata = \"M:\\Finance\\REPORTING\\2022_08\\Hóközi FC\\GL.xlsx\"
    Set Wb = Workbooks.Open(Newdata)
    ThisWorkbook.RefreshAll
    ActiveSheet.Range(\"A:AE\").AutoFilter Field:=30, Criteria1:=\"P2\"
    Windows(\"GL.xlsx\").Activate
    Range(\"A1\").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.SpecialCells(xlCellTypeVisible).Select
    Selection.Copy
End Sub

提前致谢

  • 作为一种好的做法,最好在 VBA 中避免使用 SelectActivate。您可能会发现 this post 很有用。此外,当提及Range 时,您应该使用Wb.RangeThisWorkbook.Range 以避免任何混淆。

标签: excel vba


【解决方案1】:

复制过滤范围

Option Explicit

Private Sub CommandButton1_Click()

    Const Newdata As String = "M:\Finance\REPORTING\2022_08\Hóközi FC\GL.xlsx"
    
    ThisWorkbook.RefreshAll ' irrelevant???
    
    ' Open and reference the source workbook ('swb').
    Dim swb As Workbook: Set swb = Workbooks.Open(Newdata)
    ' Reference the source worksheet ('sws').
    Dim sws As Worksheet: Set sws = swb.Worksheets("Sheet1") ' adjust!
    ' Clear filters.
    If sws.FilterMode Then sws.ShowAllData
    ' Reference the source (table) range ('srg').
    Dim srg As Range: Set srg = sws.Range("A1").CurrentRegion
    
    srg.AutoFilter Field:=30, Criteria1:="P2"
    
    srg.SpecialCells(xlCellTypeVisible).Copy
    
    ' You could e.g. do...
    'srg.SpecialCells(xlCellTypeVisible).Copy _
        ThisWorkbook.Worksheets("Sheet1").Range("A1")
    ' ... if the workbook containing this code ('ThisWorkbook')
    ' is the destination workbook.

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多