我給了兩種方法來找到最後一個單元格 - 使用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
列** K **常量中的條目是否爲公式? –
[在VBA中查找上次使用的單元時出錯]的可能重複(https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-vba) –