我尝试了几个小时来搜索并寻找可能的答案。我准备放弃。我一直无法找到一个与我所问的情景非常相似的人,也许我忽略了它。VBA:在固定数量的范围内查找最后一行
我想查找特定范围内的最后一行。范围是A7
到A21
。我希望能够将输入数据从我的表单输入到该范围内的空行...
这里是棘手的地方。我在同一张纸上还有两个其他类别,我需要输入数据。数据可能已经在这里,我想再次查找最后一行然后输入数据。范围A27:A41
。
最后一类范围A46:A66
。
希望这里有人能帮助我。
我尝试了几个小时来搜索并寻找可能的答案。我准备放弃。我一直无法找到一个与我所问的情景非常相似的人,也许我忽略了它。VBA:在固定数量的范围内查找最后一行
我想查找特定范围内的最后一行。范围是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
值应该是第一个空行的行数(的ListObject的)。
很棒的建议。表格(ListObjects)肯定会是一条路。 – Hambone
这应该让你在正确的方向...
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
等)。如果情况并非如此,那么您需要使用循环,而不是.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"
这也许是有用的:如果你使用范围(“A7”)CurrentRegion.End(xlDown)你在该地区(或区域)包含单元格A7的最后一个单元格。之后,使用Offset很容易转到下一行。 – Tom