您可以使用VBA中的COUNTA函數來實現此目的。對於動態輸出行,我強烈建議標記這些行,以便代碼可以輕鬆找到它們。在這種情況下,我通過在單元格A5中放入了「名稱計數」,並在單元格A9中放入了「學校計數」(在您發佈的第二個表格中)。這些可以在任何你想要的行中。代碼只要在列A中就可以找到它們。
爲了將來的參考,使用命名範圍將是一個更乾淨和更有效的方法。
Sub der()
'Declare and set worksheet object
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1") 'Worksheet name here
Dim nameOutRow As Integer, schoolOutRow As Integer
Dim ns As Integer, ne As Integer, ss As Integer, se As Integer
'Find the Output rows
nameOutRow = Application.Match("Name Count", ws.Columns(1), 0)
schoolOutRow = Application.Match("School Count", ws.Columns(1), 0)
'Determine Name count range
ns = Application.Match("Name", ws.Columns(1), 0) 'name start row
ne = nameOutRow - 1 'name end row
'School count range
ss = Application.Match("School", ws.Columns(1), 0) 'school start row
se = schoolOutRow - 1 'school end row
'Names
ws.Range("B" & nameOutRow) = Application.CountA(ws.Range("B" & ns & ":B" & ne))
ws.Range("C" & nameOutRow) = Application.CountA(ws.Range("C" & ns & ":C" & ne))
ws.Range("D" & nameOutRow) = Application.CountA(ws.Range("D" & ns & ":D" & ne))
'Schools
ws.Range("B" & schoolOutRow) = Application.CountA(ws.Range("B" & ss & ":B" & se))
ws.Range("C" & schoolOutRow) = Application.CountA(ws.Range("C" & ss & ":C" & se))
ws.Range("D" & schoolOutRow) = Application.CountA(ws.Range("D" & ss & ":D" & se))
End Sub
實際上,列B,C,D中的條目是動態的。因此,我無法將範圍硬編碼爲B5,C5等。@oortCloud您可以幫我解決嗎? – TanviP
@TanviP,看編輯 – oortCloud
謝謝@oortCloud!只有一個問題。我在'nameOutRow = Application.Match(「Name Count」,ws.Columns(1),0)上遇到類型不匹配錯誤''你能幫忙嗎? – TanviP