Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在excel vba中使用特定单元格中的数据计算行数_Excel_Vba - Fatal编程技术网

如何在excel vba中使用特定单元格中的数据计算行数

如何在excel vba中使用特定单元格中的数据计算行数,excel,vba,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。它始终返回1,因为您正在计算定义为单个单元格的范围内的行数。如果要从特定单元格中获取值,请使

我正在学习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。

它始终返回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
这可能有轻微的语法错误,因此如果它不运行,我将澄清/更正。

使用End
  • 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
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
可靠性较低的
xlDown

这将从给定单元格向下“查看”,并找到第一个空单元格,以使用范围返回行数

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
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

回答正确。再次谢谢你