[英]how to count the number of rows with data from a specific cell in excel vba
我只是在学习 VBA excel。 我正在编写一个代码来计算来自特定单元格的数据的行数,比如 B5
代码如下。
Sub Count_Rows()
Dim No_Of_Rows As Integer
No_Of_Rows = Range("B5").End(xlDown).Rows.Count
MsgBox No_Of_Rows
End Sub
上面的代码总是返回值 1。
Range("B5").End(xlDown)
是对后面第一个空单元格之前的单元格的引用。 所以它只有一排。 您想要返回从第一个单元格到此单元格的范围的行数。 更可靠的xlUp
这将从工作表最底部的单元格向上“查找”并找到第一个空单元格以使用该范围返回行数。
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
不太可靠的xlDown
这将从给定单元格向下“查看”并找到第一个空单元格以使用该范围返回行数。
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
它始终返回 1,因为您正在计算已定义为单个单元格的范围内的行数。 如果您想要来自特定单元格的值,则使用.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
这可能有轻微的语法错误,所以如果它没有运行,我会澄清/纠正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.