如何使用VBA从特定的Excel单元格迭代到此列中具有值的最新行?

问题描述 投票:-1回答:3

我是Excel和VBA宏的新手,我有以下问题。

我编写了这段代码,用于打印从第3行到第5行的K列单元格的内容:

Dim outQuantityRange As Range
Set outQuantityRange = Range("K3:K5")


For Each currentOutQuantity In outQuantityRange.Cells
    MsgBox (currentOutQuantity)

它工作正常。我的问题是我希望更改此代码以从第3行开始到最后插入的值开始访问K列中的单元格内容。例如,如果最后一个值进入K100单元格,则必须打印以下内容:K3,K4,K5,......,K100。

我不想指定K100,但它必须停止到K列中具有值的最后一行。

我该如何实现这种行为?下一个

excel vba excel-vba
3个回答
1
投票

如果K3和最后一行之间没有间隙,那么这将完成工作:

Dim rng As Range
Set rng = Range("K3", Range("K3").End(xlDown))

1
投票

我已经给出了两种方法来找到最后一个单元格 - 使用LastCell函数将返回工作表上最后一个单元格,该单元格可能不在K列中。

我展示的第二种方法是找到K列中的最后一个单元格。

然后通过用逗号分隔第一个和最后一个单元格引用来设置范围。

Sub AllValues()

    Dim outQuantityRange As Range
    Dim currentOutQuantity As Range
    Dim rLastCell As Range

    With ThisWorkbook

        'Find last cell on sheet containing data.
        'Set rLastCell = LastCell(.Worksheets("MySheetName"))

        With .Worksheets("MySheetName")
            'Find last cell in column K containing data.
            Set rLastCell = .Cells(.Rows.Count, 11).End(xlUp)
            Set outQuantityRange = .Range("K3", rLastCell)
        End With
    End With

    For Each currentOutQuantity In outQuantityRange
        MsgBox currentOutQuantity, vbOKOnly + vbInformation
    Next currentOutQuantity

End Sub

Public Function LastCell(wrkSht As Worksheet) As Range

    Dim lLastCol As Long, lLastRow As Long

    On Error Resume Next

    With wrkSht
        lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
        lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row

        If lLastCol = 0 Then lLastCol = 1
        If lLastRow = 0 Then lLastRow = 1

        Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
    End With
    On Error GoTo 0

End Function

1
投票

如果列K中的值是常量,则:

Sub qwerty()
    Dim outQuantityRange As Range, zell As Range

    Set outQuantityRange = Range("K3:K" & Rows.Count).SpecialCells(2)

    For Each zell In outQuantityRange.Cells
        MsgBox zell.Value
    Next zell
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.