VBA:查找固定数量范围的最后一行

时间:2015-12-24 10:51:15

标签: excel excel-vba vba

我尝试了几个小时来搜索并寻找可能的答案。我准备放弃了。我找不到一个像我要问的情景的人,也许我忽略了它。

我想找到特定范围内的最后一行。范围为A7A21。我希望能够将表单中的输入数据输入到该范围内的空行...

这是棘手的地方。我在同一张纸上还有两个其他类别,我需要输入数据。数据可能已经在这里,我想再找到最后一行然后输入数据。范围A27:A41

最后一个类别的范围为A46:A66

希望有人可以帮助我。

3 个答案:

答案 0 :(得分:2)

在工作表上定义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的值应该是第一个空行的行号(列表对象)。

答案 1 :(得分:0)

这应该让你指向正确的方向......

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。您肯定需要根据您的情况进行调整,尤其是当您的范围内的所有单元格都填满时的逻辑。

答案 2 :(得分:0)

为了使您的请求更通用(因此可伸缩),您可以创建一个函数来查找任何给定范围的第一个可用行:

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"