9

I have looked at the suggested questions to find the answer to my problem. The closest question is called: Count number of rows in a different Excel Sheet Count number of rows in a different Excel Sheet

The solution to that problem does not work for me.

I am trying to count the number of rows in a range in a different worksheet than the active worksheet. Here is my code:

Sub verbflashcards()

Dim wordcount As Long

With Worksheets("Verbs")
wordcount = .Range(Cells(4, 1), Cells(4, 1).End(xlDown)).Rows.Count
End With

MsgBox (wordcount)
End Sub

I have a worksheet called Verbs and it is the second worksheet in the workbook. I have tried:

With Verbs
With Sheet2
With Sheets("Verbs")
With Sheets("Sheet2") 

None of them seem to work.

Community
  • 1
  • 1
user2859603
  • 235
  • 4
  • 9
  • 18

2 Answers2

14

Your original was not working because the parent of Cells(4, 1) and Cells(4, 1).End(xlDown) was not specified. Prefix any cell address with a period (aka . or full stop) when you are inside a With ... End With block. Example:

With Worksheets("Verbs")
  wordcount = .Range(.Cells(4, 1), .Cells(4, 1).End(xlDown)).Rows.Count
End With

Note the .Cells(4, 1) and not Cells(4, 1). The period specifies that the cell(s) you are referring to are within Worksheets("Verbs").

4

Check this and hope this will help you:

Sub verbflashcards()

Dim wordcount As Long

wordcount = ActiveWorkbook.Worksheets("Verbs").Range("A4", Worksheets("Verbs").Range("A4").End(xlDown)).Rows.Count

MsgBox (wordcount)

End Sub

Where, D1 is the column from which you can get row count.

Method 2:

Sub verbflashcards()

Dim wordcount As Long
With Sheets("Verbs")
    wordcount = .Range("A" & .Rows.Count).End(xlUp).Row
End With

MsgBox (wordcount)
End Sub

Note: There are lots of answers to your questions. Check this SO link: How can I find last row that contains data in the Excel sheet with a macro?

Community
  • 1
  • 1
Paresh J
  • 2,401
  • 3
  • 24
  • 31
  • It works! So worksheets has to be referenced a second time inside the range? – user2859603 Jan 04 '15 at 07:01
  • 1
    There are couple of methods available to achieve the same., you can choose any one. Check my edited answer. – Paresh J Jan 04 '15 at 07:06
  • 1
    I think `.Range("D1"...` was intended to be `.Range("A4"...`. It seems you transposed the *r* and *c* from `Cells(4, 1)`. –  Jan 04 '15 at 07:20
  • 1
    That is not necessarily the number of used rows - it is the last row with data in column A (A1 could be blank etc). – brettdj Jan 04 '15 at 10:03