excel vba选择表的范围

时间:2018-01-18 07:54:13

标签: excel vba excel-vba

我想选择一个表,它将有固定的列(其中4个),但也可以有任意数量的行,空行。我如何选择表格范围?

enter image description here

例如,当前选择为B2 to E5

如何在VBA中以编程方式获取此内容?

3 个答案:

答案 0 :(得分:4)

以下是如何设置对表的引用。你应该看:Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)。它将使您更好地了解范围,工作表和Excel对象模型。

Dim Target As Range
With Worksheets("SheetName")
    Set Target = .Range("B2:E2", .Range("B" & .Rows.Count).End(xlUp))
End With

答案 1 :(得分:1)

试,

Worksheets("Sheet3").Range("Table1[#All]").Select
'or,
Worksheets("Sheet3").ListObjects("Table1").Range.Select

答案 2 :(得分:1)

假设您的表始终以B2开头并且总是宽度为4列,您可以使用类似的内容来获取所有4列的lastrow:

Function getlastrow() As Integer
    Dim i As Integer
    getlastrow = 0
    With Worksheets("YourWorksheet")
        For i = 0 To 3
            'starting with 2+i=2 (column B) and End with 2+i=5 (column E)
            If (.Cells(.Rows.Count, 2 + i).End(xlUp).Row) > getlastrow Then 
                getlastrow = .Cells(.Rows.Count, 2 + i).End(xlUp).Row
            End If
        Next i
    End With
End Function

根据这些信息,您可以设置范围:

Sub SetRange()
    Dim myrange As Range
    With Worksheets("Tabelle1")
        Set myrange = .Range("B2:E" & getlastrow)
    End With
End Sub