[英]how to count the number of rows with data from a specific cell in excel vba
I am just learning VBA excel.我只是在学习 VBA excel。 I am writing a code to count number of rows with data from specific cell say B5我正在编写一个代码来计算来自特定单元格的数据的行数,比如 B5
the code as follows.代码如下。
Sub Count_Rows()
Dim No_Of_Rows As Integer
No_Of_Rows = Range("B5").End(xlDown).Rows.Count
MsgBox No_Of_Rows
End Sub
the above code always returns the value 1.上面的代码总是返回值 1。
Range("B5").End(xlDown)
is a reference to the cell before the first following empty cell. Range("B5").End(xlDown)
是对后面第一个空单元格之前的单元格的引用。 So it has only one row.所以它只有一排。 You want to return the number of rows of the range from the first cell to this cell.您想要返回从第一个单元格到此单元格的范围的行数。 The More Reliable xlUp
更可靠的xlUp
This will 'look' from the bottom-most cell of the worksheet upward and find the first empty cell to use the range to return the number of rows.这将从工作表最底部的单元格向上“查找”并找到第一个空单元格以使用该范围返回行数。
Sub countRowsUp()
Dim No_Of_Rows As Long
No_Of_Rows = Range("B5", Range("B" & Rows.Count).End(xlUp)).Rows.Count
'No_Of_Rows = Range(Range("B5"), Range("B" & Rows.Count).End(xlUp)).Rows.Count
MsgBox No_Of_Rows
End Sub
The Less Reliable xlDown
不太可靠的xlDown
This will 'look' from the given cell downward and find the first empty cell to use the range to return the number of rows.这将从给定单元格向下“查看”并找到第一个空单元格以使用该范围返回行数。
Sub countRowsDown()
Dim No_Of_Rows As Long
No_Of_Rows = Range("B5", Range("B5").End(xlDown)).Rows.Count
'No_Of_Rows = Range(Range("B5"), Range("B5").End(xlDown)).Rows.Count
MsgBox No_Of_Rows
End Sub
It is always returning 1 because you are counting the number of rows in a range that you have defined as a single cell.它始终返回 1,因为您正在计算已定义为单个单元格的范围内的行数。 If you want the value from a specific cell you use .Range("B5").Value
and if you want to check if all the rows in a certain set of cells have that value (lets say B10-B100) you read it into a variable and loop through it:如果您想要来自特定单元格的值,则使用.Range("B5").Value
并且如果您想检查某个单元格集中的所有行是否具有该值(比如说 B10-B100),则将其读入一个变量并循环遍历它:
Dim wS As Worksheet
Dim searchArea as Range
Dim c as Range
Dim vl As Variant
Dim No_Of_Rows as Integer
Set wS = ActiveSheet
Set searchArea = wS.Range("B10:B100")
vl = wS.Range("B5").Value
No_Of_Rows = 0
For Each c in searchArea
If (c.Value = vl) Then
No_Of_Rows = No_Of_Rows + 1
End If
Next
MsgBox No_Of_Rows
This might have slight syntax errors so if it doesn't run I will clarify/correct.这可能有轻微的语法错误,所以如果它没有运行,我会澄清/纠正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.