简体   繁体   中英

Counting the number of rows in an non-active sheet

I have 2 sheets within a workbook. sheet 1 is where i am calling the macro from.

Within sheet 2 i want to loop through the rows and print "YES" if it was sucsessful.

So far i have the below:

Dim TotalNumRows As Long
Dim noRow As Integer
With Sheets("Sheet2")
'get the amount of rows within Q3 Joiners list
TotalNumRows = .Range("B" & .Rows.Count).End(xlUp).Row

.Range("B2").Select

For userRowNo = 1 To TotalNumRows

MsgBox ("Yes")
 ActiveCell.Offset(1, 0).Select
  Next

End With

Its calculating the amount of rows within sheet 2 but an error is thrown on the '.Range("B2").Select'saying "Select method of range class failed"

you can select a range only on active worksheets

Sub main()
    Dim TotalNumRows As Long
    Dim noRow As Integer

    With Sheets("Sheet2")
        .Activate '<-- activate relevant worksheet
        'get the amount of rows within Q3 Joiners list
        TotalNumRows = .Range("B" & .Rows.Count).End(xlUp).Row

        .Range("B2").Select

        For noRow = 1 To TotalNumRows
            MsgBox ("Yes")
            ActiveCell.Offset(1, 0).Select
        Next
    End With
End Sub

Do you want to select B2 in Sheet2? In that case, you need to activate the sheet first with .Activate(). You can only select things on the active sheet. Otherwise, remove the line.

In general, you're better off not using .Select or .Activate as a VBA best practice due to the performance hits and difficulties in debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM