excel 行数不正确

bqucvtff  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(230)

我有: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
fjaof16o

fjaof16o1#

  • 示例 *
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
wa7juj8i

wa7juj8i2#

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

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

相关问题