[英]Excel VBA Get Count of Non-Empty Rows in Range
I know this has been asked at least a dozen times, but of all those questions the solutions seemed to be tailored or simply created an error in my code. 我知道这已被问到至少十几次了,但是在所有这些问题中,解决方案似乎都是量身定制的,或者只是在我的代码中创建了一个错误。 For some reason I get an error when I try and reference a range from a different worksheet. 出于某种原因,当我尝试从不同的工作表中引用范围时,我收到错误。 Below is my code. 以下是我的代码。 I have two worksheets (tabs). 我有两个工作表(标签)。 One has a button to launch my code MENU
, the other is the data I am trying to read and write to RAW
. 一个按钮用于启动我的代码MENU
,另一个是我尝试读取和写入RAW
。 All I am trying to do is find out how many rows of data the sheet has so I can loop through the rows and make changes. 我想要做的就是找出工作表有多少行数据,这样我就可以循环遍历行并进行更改。 For some reason I can't wrap my head around it or something. 出于某种原因,我无法绕过它或其他东西。
Private Sub CommandButton21_Click()
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Set wbCurrent = ThisWorkbook
Set wsCurrent = wbCurrent.Worksheets("RAW")
Dim i As Long
Dim siteCol As Long
siteCol = Range("I" & Rows.Count).End(xlUp).Row
For i = 1 To siteCol
wsCurrent.Range("I" & i) = "MARKED"
Next i
Range("I1") = siteCol
End Sub
1- Always use Long
for your variables, not Integer
unless you have a specific reason. 1-除非您有特定原因,否则始终对您的变量使用Long
,而不是Integer
。 The maximum value of an Integer
is 32767 , which might be not enough to hold your count of rows. Integer
的最大值是32767 ,这可能不足以保存您的行数。
2- Dont get the number of rows with COUNTA
, this has many drawbacks. 2-不要用COUNTA
获得行数,这有很多缺点。 use this instead: 改用它:
siteCol = wsCurrent.Range("I" & wsCurrent.Rows.count).End(xlUp).Row
This finds the Row number of the last occupied cell in wsCurrent
, assuming that wsCurrent
is at the top of the document (it starts on Row 1). 这将找到wsCurrent
最后一个被占用单元格的行号,假设wsCurrent
位于文档的顶部(它从第1行开始)。 Please note that if wsCurrent is completely empty, this will find the row number of the first occupied cell above wsCurrent
, or the first row of the document. 请注意,如果wsCurrent完全为空,则会在 wsCurrent
或文档的第一行上找到第一个被占用单元格的行号。
3- When you want to assign a whole range to the same value, you can do it at once, which is much faster and simpler, like this (no loop needed): 3-如果要将整个范围分配给相同的值,可以立即执行,这样更快更简单,就像这样(不需要循环):
wsCurrent.Range("I1:I" & siteCol) = "MARKED"
4- No need to Activate
a worksheet to work with it. 4-无需Activate
工作表即可使用它。 Drop the statement wsCurrent.Activate
and try to always work with qualified ranges. 删除语句wsCurrent.Activate
并尝试始终使用限定范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.