Rows.count不正确

时间:2018-01-29 08:36:20

标签: excel vba excel-vba

我有:N = Cells(Rows.Count, "B").End(xlUp).Row 当我有一个包含200k +行的数据集时,它会一直返回1。

非常奇怪,因为只有这个工作簿,就像另一个工作簿这条线一样。

问题:

有关为何发生这种情况的任何建议? 任何可能的工作?我目前的工作是:

Sub Macro2()

    Range("B1").Select
    Selection.End(xlDown).Select
    Selection.End(xlDown).Select
    Selection.End(xlUp).Select
    n = ActiveCell.Row
End Sub

2 个答案:

答案 0 :(得分:4)

实施例

Option Explicit
Private Sub Example()
    With ThisWorkbook.Worksheets(1)
        Dim LAST_ROW As Long
            LAST_ROW = .Range("A" & .Rows.Count).End(xlUp).Row

        Debug.Print LAST_ROW ' Print on Immediate Window
    End With
End Sub

查找最后一行的多种方式

Private Sub Example2()
    Dim Sht As Worksheet
    Set Sht = ActiveWorkbook.Sheets(1)

    Dim LAST_ROW As Long

    'Using Find
      LAST_ROW = Sht.Cells.Find("*", searchorder:=xlByRows, _
                                     searchdirection:=xlPrevious).Row

    'Using SpecialCells
      LAST_ROW = Sht.Cells.SpecialCells(xlCellTypeLastCell).Row

    'Ctrl + Shift + End
      LAST_ROW = Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row

    'UsedRange
      LAST_ROW = Sht.UsedRange.Rows(Sht.UsedRange.Rows.Count).Row

    'Using Named Range
      LAST_ROW = Sht.Range("MyNamedRange").Rows.Count

    'Ctrl + Shift + Down
      LAST_ROW = Sht.Range("A1").CurrentRegion.Rows.Count

End Sub

答案 1 :(得分:1)

我假设您希望代码在活动(选定)工作表中运行。示例:

Option Explicit
Sub LastrowExample()
'declare variable lastrow as Long
Dim lastrow As Long
'get lastrow:
lastrow = Cells(Rows.Count, 2).End(xlUp).Row 
'or lastrow = Cells(Rows.Count, "B").End(xlUp).Row
End sub

应该有效。 但是我总是首先至少指定表单,以确保我的代码可以在任何地方运行,例如:

Option Explicit
Sub LastrowExample2()
'declare variable lastrow as Long
Dim lastrow as Long
'declare sheet
 Dim ws As Worksheet
'get sheet
Set ws = ThisWorkbook.Worksheets("mysheetname") 
'get lastrow:
With ws
lastrow = .Cells(Rows.Count, 2).End(xlUp).Row 
'or lastrow = .Cells(Rows.Count, "B").End(xlUp).Row
End With
End sub