获取包含给定范围数据的所有cels

时间:2016-09-12 12:56:13

标签: vba excel-vba excel

在我的excel中,从A41到M41 向下,我将拥有数据。在我的列表框中,我希望看到我将拥有的所有数据,而不仅仅是第70行(就像我的代码一样)。我知道我必须使用xlUP,但我不知道如何。我将从A41开始有500行:M41,我必须看到它们。 这是我的代码到第70行(具体范围):

Private Sub UserForm_Activate()
    Dim lb As msforms.ListBox
    Dim rcArray() As Variant
    Dim lrw As Long, lcol As Long
    Dim rngTarget As Range

    Set rngTarget = Worksheets("Sheet1").Range("A41:M70")

    ReDim Preserve rcArray(1 To rngTarget.Rows.Count, 1 To rngTarget.Columns.Count)
    With rngTarget
        For lcol = 1 To .Columns.Count
            For lrw = 1 To .Rows.Count
                rcArray(lrw, lcol) = rngTarget.Cells(lrw, lcol)
            Next lrw
        Next lcol
    End With
    Set lb = Me.ListBox1
    With lb
        .ColumnCount = 13
        .ColumnWidths = "50;80;100"
        .List = rcArray
    End With

1 个答案:

答案 0 :(得分:1)

你实际上比想象的更接近答案。这将找到A列中的最后一个单元格,然后创建一个字符串值以将范围设置为A41:M(LastRow)

Sub Find_the_Last_Row()

Dim lastRow As Long
Dim strRange As String
DimrngTarget As Range

With ActiveSheet
    lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
End With

strRange = "(A41:M" & lastRow & ")"

Set rngTarget = ActiveSheet.Range(strRange)

End Sub