[英]VBA: Find last row in a fixed number of ranges
我嘗試了幾個小時,以尋找可能的答案。 我准備放棄。 我沒有找到一種情況與我要問的情況很像的人,也許我忽略了它。
我想在特定范圍內找到最后一行。 范圍是A7
至A21
。 我希望能夠將表單中的輸入數據輸入該范圍內的空行...
這是棘手的地方。 我還需要在同一張紙上輸入數據的其他兩個類別。 數據可能已經在這里,再次我想找到最后一行,然后輸入數據。 范圍A27:A41
。
最后一個類別是A46:A66
。
希望這里有人可以幫助我。
在工作表上的Excel中定義用作表格的范圍。 然后在您的代碼中使用:
Dim Table1 As listObject, Table2 As ListObject
With ThisWorkbook.Worksheets("Name of the sheet the tables are on")
Set Table1 = .ListObjects("Name of the table")
Set Table2 = .ListObjects("Name of the table")
End With
Dim LastRowT1 As Long, LastRowT2 As Long
LastRowT1 = 1: LastRowT2 = 1
Do Until Table1.DataBodyRange(LastRowT1, 1) = Empty
LastRowT1 = LastRowT1 + 1
Loop
Do Until Table2.DataBodyRange(LastRowT2, 1) = Empty
LastRowT2 = LastRowT2 + 1
Loop
'If you run out of space and automatically want to add an extra row add
'the following code.
If LastRowT1 > Table1.ListRows.Count Then
Table2.ListRows.Add AlwaysInsert:=True
End If
If LastRowT2 > Table2.ListRows.Count Then
Table2.ListRows.Add AlwaysInsert:=True
End If
LastRowT1 and LastRowT2
的值應為第一個空行的(列表對象的)行號。
這應該使您指向正確的方向...
Sub Main()
Dim r1 As Range
Dim r2 As Range
Dim r3 As Range
Dim rFind As Range
'Set your range vars
Set r1 = Range("A7:A21")
Set r2 = Range("A27:A41")
Set r3 = Range("A46:A66")
'Find the next empty cell and display the address
On Error Resume Next
'First range
Set rFind = r1.Find("*", searchdirection:=xlPrevious).Offset(1, 0)
If Not rFind Is Nothing Then
MsgBox "First open cell in " & r1.Address & " is " & rFind.Address
Else
MsgBox "First open cell in " & r1.Address & " is " & r1.Cells(1, 1).Address
End If
'Second range
Set rFind = r2.Find("*", searchdirection:=xlPrevious).Offset(1, 0)
If Not rFind Is Nothing Then
MsgBox "First open cell in " & r2.Address & " is " & rFind.Address
Else
MsgBox "First open cell in " & r2.Address & " is " & r2.Cells(1, 1).Address
End If
'Third range
Set rFind = r3.Find("*", searchdirection:=xlPrevious).Offset(1, 0)
If Not rFind Is Nothing Then
MsgBox "First open cell in " & r3.Address & " is " & rFind.Address
Else
MsgBox "First open cell in " & r3.Address & " is " & r3.Cells(1, 1).Address
End If
End Sub
假設您從上到下填充單元格(例如,首先填充A7
,然后填充A8
,然后填充A9
, A9
)。 如果不是這種情況,那么您需要使用循環來代替.Find
。 您肯定需要使這種情況適應您的情況,尤其是范圍內所有單元格都填滿時的邏輯。
為了使您的請求更加通用(從而可擴展),您可以創建一個函數以查找任何給定范圍的第一行:
Function FindFirstOpenCell(ByVal R As Range) As Integer
Dim row, col As Integer
row = R.row
col = R.Column
FindFirstOpenCell = Cells(row + R.Rows.Count - 1, col).End(xlUp).row + 1
End Function
從這里您可以簡單地反復調用該函數:
Dim row As Integer
row = FindFirstOpenCell(Range("A7:A21"))
Cells(row, 1).Value = "My Next Item"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.