Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

vba - Count the number of rows in another sheet

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...