2017-12-27 628 views
-1

我是绝对新的Excel和宏VBA我有以下问题。如何使用VBA从特定的Excel单元格迭代到此列中具有值的最新行?

我写了这个代码打印从3TH行开始到第5行的ķ列单元格的内容:

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列的最后一行。

我该如何实现这种行为? 接下来

+0

列** K **常量中的条目是否为公式? –

+2

[在VBA中查找上次使用的单元时出错]的可能重复(https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-vba) –

回答

1

如果有K3和最后一排之间没有间隙,那么这将做的工作:

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

使用'xlDown'将返回'K $ 3:$ K $ 1048576'如果'K3'具有列中的唯一值。 –

+0

@ DarrenBartrup-Cook这些都是“猜游戏”。 – JohnyL

+0

我不知道这意味着什么。 –

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 
相关问题