在Excel VBA中,如何计算两个表之间的行数?

时间:2016-07-25 10:29:39

标签: excel vba excel-vba

我有两个表,这两个表之间的行数各不相同。如何识别两个表之间存在的行数?

2 个答案:

答案 0 :(得分:0)

您的意思是累积还是分开?

<强>单独: 在表格的任何位置选择一个单元格,然后选择:

Activecell.CurrentRegion.Rows.Count

累积地我需要更多信息,如表名或范围等。

答案 1 :(得分:0)

你应该处理两个ListObject表,并想知道它们定义的范围之间的行距离,然后你可以使用:

Function RowsBetweenTables(Table1 As ListObject, Table2 As ListObject) As Long
    Dim tempLong As Long

    If Intersect(Table1.Range.EntireRow, Table2.Range.EntireRow) Is Nothing Then
        tempLong = Table2.Range.Rows(1).Row - Table1.Range.Rows(Table1.Range.Rows.Count).Row - 1
        Select Case tempLong
            Case 0
                RowsBetweenTables = 0
            Case Is < 0
                RowsBetweenTables = Table1.Range.Rows(1).Row - Table2.Range.Rows(Table2.Range.Rows.Count).Row - 1
            Case Is > 0
                RowsBetweenTables = tempLong
        End Select
    Else
        RowsBetweenTables = -1
    End If
End Function

被利用为:

Sub main()
    Dim Table1 As ListObject, Table2 As ListObject
    Dim nRows As Long

    With Worksheets("Tables") '<--| change "Tables" with your actual sheet with tables name
        Set Table1 = .ListObjects("Table1") '<--| change "Table1" with your actual first table name
        Set Table2 = .ListObjects("Table2") '<--| change "Table1" with your actual second table name
    End With

    nRows = RowsBetweenTables(Table1, Table2)
    If nRows >= 0 Then
        MsgBox "there are " & nRows & " rows between tables"
    Else
        MsgBox "no rows between tables!"
    End If
End Sub