我有一张这样的表:
A1 B1 Team 1 C1 Team 2 D1 Team 3
A2 Name B2 A C2 B D2 C
A3 B3 D C3 E D3 F
A4 B4 G C4 D4 H
A5 School B5 AB C5 CD D5
A6 B6 GH C6 EF D6
A7 B7 C7 IJ D7
我试图编写一个宏来获取非空白行的计数,如下所示:
A1 B1 Team 1 C1 Team 2 D1 Team 3
A2 Name B2 A C2 B D2 C
A3 B3 D C3 E D3 F
A4 B4 G C4 D4 H
A5 B5 3 C5 2 D5 3
A6 School B6 AB C6 CD D6
A7 B7 GH C7 EF D7
A8 B8 C8 IJ D8
A9 B9 2 C9 3 D9 0
其中第5行和第9行给出非空行的计数。 我需要使用宏来做到这一点。
答案 0 :(得分:1)
您可以使用VBA中的COUNTA功能实现此目的。对于动态输出行,我强烈建议标记这些行,以便代码可以轻松找到它们。在这种情况下,我通过在单元格A5中放置“Name Count”,在单元格A9中放置“School Count”(在您发布的第二个表中)来完成此操作。这些可以在你想要的任何一行。只要它们在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