行计数器仅计数?顶排

时间:2019-01-09 20:51:47

标签: excel vba rowcount

我的代码应该从表的顶部到包含J列中包含文本的最底部的行选择A-H中的所有项目。但是,现在要做的就是选择第一行。这段代码在其他地方可以很好地用于其他目的,但是当我在此处运行它时,它只会选择第一行。

这是代码及其当前功能。注释掉的位代替其他finalrow =语句时,其作用相同。

Option Explicit

Sub FindRow()

Dim reportsheet As Worksheet
Dim finalrow As Integer

Set reportsheet = Sheet29

Sheet29.Activate
'finalrow = Cells(Rows.Count, 10).End(xlUp).Row
finalrow = Range("J1048576").End(xlUp).Row


    If Not IsEmpty(Sheet29.Range("B2").Value) Then
         Range(Cells(1, 1), Cells(finalrow, 8)).Select

    End If
End Sub

enter image description here

这是带有行计数器的代码摘录。

datasheet.Select
finalrow = Cells(Rows.Count, 1).End(xlUp).Row

''loop through the rows to find the matching records
For i = 1 To finalrow
    If Cells(i, 1) = item_code Then ''if the name in H1 matches the search name then
        Range(Cells(i, 1), Cells(i, 9)).Copy ''copy columns 1 to 9 (A to I)
        reportsheet.Select ''go to the report sheet
        Range("A200").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False ''find the first blank and paste info there
        datasheet.Select ''go back to the data sheet and continue searching
        End If
Next i

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

Option Explicit
Sub FindRow()

    ' always use Longs over Integers
    Dim finalrow As Long: finalrow = 1

    ' you might not need this line tbh
    Sheet29.Activate

    With Sheet29

        ' custom find last row
        Do While True
            finalrow = finalrow + 1
            If Len(CStr(.Range("J" & finalrow).Value)) = 0 Then Exit Do
        Loop

        ' Len() is sometimes better then IsEmpty()
        If Len(CStr(.Range("B2").Value)) > 0 Then
            .Range(.Cells(1, 1), .Cells((finalrow - 1), 8)).Select
        End If
    End With

End Sub