如何获得从A2到终点的范围(无选择语句)

时间:2019-01-03 18:24:19

标签: excel vba

我正在尝试从一个工作簿复制并粘贴到另一工作簿,但是我收到Range类的Autofilter方法失败错误。我发现未指定结束行时会发生此错误。例如,如果我的复制数据字段在行500处结束,则必须精确设置范围(A2,AJ500)。但是,该数据(结束行)可以每月更改。可以是AJ700,AJ600等。有没有办法使我的范围(A2,结束行)并使宏运行而不会出现Range类失败错误?

如果您不清楚我的问题,请告诉我。谢谢。

Option Explicit

Sub Macro1()


    Dim wb As Workbook, wbO As Workbook
    Dim ws As Worksheet, wsO As Worksheet


    Set wb = ThisWorkbook

    Set ws = wb.Sheets("Copyingfrom")


    Set wbO = Workbooks.Add("Output.xlsm")


    With wbO

        Set wsO = wbO.Sheets("OutputSheet")
        ActiveSheet.AutoFilterMode = False

With ws.Range("A2:AJ500") --> this is the field that I want to run as something like (A2:end) 

        .AutoFilter Field:=36, Criteria1:="1"
        .SpecialCells(xlCellTypeVisible).Copy
        End With

        wsO.Range("I3").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    End With


End Sub

2 个答案:

答案 0 :(得分:0)

复制到工作簿

代码

Option Explicit

Sub CopyRange()

    Dim ws As Worksheet, wsO As Worksheet
    Dim lngLastRow As Long

    Set ws = ThisWorkbook.Sheets("Copyingfrom")
    Set wsO = Workbooks("Output.xlsm").Sheets("OutputSheet")

    With ws
        lngLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        With .Range("A2:AJ" & lngLastRow)
            .AutoFilter Field:=36, Criteria1:="1"
            .SpecialCells(xlCellTypeVisible).Copy
        End With
        wsO.Range("I3").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        .AutoFilterMode = False
    End With

    Application.CutCopyMode = False

End Sub

答案 1 :(得分:0)

最简单的方法:

With ws.Range("A2").CurrentRegion ...

这将自动定义您的范围,无论最后一行在哪。