[英]Loop through counting rows and paste row count to a specific cell
I have a selection of data that has a dynamic number of columns, and under each column there is a dynamic list of values. 我选择了具有动态列数的数据,并且在每列下都有一个动态值列表。
I want to go through each column and count the number of items minus the two header fields and place it that count as a value in a specific position. 我想遍历每一列并计算减去两个标头字段的项目数,并将其作为一个值放置在特定位置。
So I have two rows of headers and then a blank row and then the data. 所以我有两行标题,然后是空白行,然后是数据。
Private Sub Worksheet_Activate()
Dim LastCol As Integer
Dim I As Long
Dim RC As Long
With ActiveSheet
LastCol = Cells(2, Columns.Count).End(xlToLeft).Column
End With
For I = 1 To LastCol
RC = Range("I:I" & Rows.Count).End(xlUp).Row
Cells(3, I).Value = RC
Next I
End Sub
I know the problem is in the loop section but I don't know how to call the rows in a number format. 我知道问题出在循环部分,但我不知道如何以数字格式调用行。
What this does: If I understood the question correctly. 它的作用:如果我正确理解了这个问题。 This will skip the two header rows, and count to see how many rows have data in them for each column. 这将跳过两个标题行,并进行计数以查看每列中有多少行数据。 Then place the count in the third row on each column. 然后将计数放在每一列的第三行中。
You've got a few issues: 您遇到了一些问题:
It's a good practice to always access the properties by using a "." 始终使用“。”访问属性是一个好习惯。 Like, LastCol = .Cells. 就像LastCol = .Cells。
You ended your With Statement too soon. 您过早地结束了“声明”。
If you are using a variable to iterate through the columns, you should use .Cells, instead of Range, and use the column number instead of Letters. 如果使用变量来遍历列,则应使用.Cells而不是Range,并使用列号而不是Letters。
You should use Long type variables for loops and row counts instead of Integer. 您应将Long类型变量用于循环和行计数,而不要使用Integer。
You might want to put this code in a module, and then just call it from the worksheet activate event. 您可能希望将此代码放在模块中,然后仅从工作表Activate事件中调用它。 That way you can call it from a button or any other time, if you need to update the counts. 这样,如果您需要更新计数,则可以从按钮或任何其他时间调用它。
The Count should = RC - 3 to account for the header rows. 计数应= RC-3以说明标题行。
In the worksheet code: 在工作表代码中:
Private Sub Worksheet_Activate()
Call CountColumnRows
End Sub
Then in a module, place this: Allowing you to call it from any source, and at any time. 然后将其放置在模块中:允许您随时随地从任何源调用它。
Sub CountColumnRows()
Dim LastCol As Long, I As Long, RC As Long
With ActiveSheet
LastCol = .Cells(2, Columns.count).End(xlToLeft).column
For I = 1 To LastCol
RC = .Cells(Rows.count, I).End(xlUp).row 'I as variable column Number
.Cells(3, I).Value = RC - 3 'Compensate for the headers and Count Row
Next I
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.