[英]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.