VBA总范围

时间:2017-05-24 12:36:11

标签: vba excel-vba range cells excel

我想在工作表中选择整个数据(整个范围)。我不知道为什么会发生错误:
Range("A1:(Cells(ostatnia_dana, ostatnia_dana1)").Select

Sub ranging()
    Dim ostatnia_dana As Integer
    Dim ostatnia_dana1 As Integer
    ostatnia_dana = Cells(Rows.Count, 2).End(xlUp).Row
    ostatnia_dana1 = Cells(2, Columns.Count).End(xlToLeft).Column
    Range("A1:(Cells(ostatnia_dana, ostatnia_dana1)").Select
End Sub

1 个答案:

答案 0 :(得分:3)

这是一个非常脏的解决方案。 像我的例子中那样更改最后一行。 :)

Option Explicit

Sub ranging()

    Dim ostatnia_dana As Integer
    Dim ostatnia_dana1 As Integer
    ostatnia_dana = Cells(Rows.Count, 2).End(xlUp).Row
    ostatnia_dana1 = Cells(2, Columns.Count).End(xlToLeft).Column
    Range(Cells(1, 1), Cells(ostatnia_dana, ostatnia_dana1)).Select

End Sub

这好一点:

Option Explicit

Sub ranging()

    Dim ostatnia_dana   As Long
    Dim ostatnia_dana1  As Long

    With ActiveSheet
        ostatnia_dana = .Cells(.Rows.Count, 2).End(xlUp).Row
        ostatnia_dana1 = .Cells(2, .Columns.Count).End(xlToLeft).Column
        .Range(.Cells(1, 1), .Cells(ostatnia_dana, ostatnia_dana1)).Select
    End With

End Sub

第二种解决方案有什么好处:

一般情况下,如果没有With ActiveSheet部分,它会很好地工作,但是如果你引用另一张不是活动的工作表,它就会失败。一般情况下,假设您有一些其他活动表,并且您想要选择名为MyWorksheetName的工作表。然后以下工作:

Option Explicit

Sub MyRanges()

    Dim ostatnia_dana   As Long
    Dim ostatnia_dana1  As Long

    Dim ws              As Worksheet

    Set ws = Worksheets("MyWorksheetName")

    With ws

        ostatnia_dana = .Cells(Rows.Count, 2).End(xlUp).Row
        ostatnia_dana1 = .Cells(2, Columns.Count).End(xlToLeft).Column

        .Select
        .Range(.Cells(1, 1), .Cells(ostatnia_dana, ostatnia_dana1)).Select

    End With

End Sub