2017-12-27 632 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 
相關問題