vba 当VBA在其间插入行时,如何计算行数并将其作为条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7388296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:00:17  来源:igfitidea点击:

How to count number of rows and make it as a condition when VBA inserts rows in between?

vbaexcel-vbaexcel

提问by niko

I Need to use a loop in my code and at a certain condition I will insert row.

我需要在我的代码中使用循环,并且在特定条件下我将插入行。

Rowz = activesheet.Cells(Rows.Count, 1).End(xlUp).Row
for j=3 to Rowz ' say number of rowz=1000

But as rows are inserted in between So the number of rows are increased. Say for example at the 200th row I insert 4 rows and 500th row I insert 10 rows So the number is increased to more than 1000 now so the loop tests till 1000 ignoring the remaining rows which are pushed down due to inserting. But I need to perform that loop till the last row even rows are inserted in between

但是当行插入在它们之间时,行数会增加。例如,在第 200 行我插入 4 行和第 500 行我插入 10 行所以现在数字增加到超过 1000,所以循环测试直到 1000 忽略由于插入而被推下的剩余行。但我需要执行该循环,直到最后一行甚至行插入其中

I thought to use these

我想用这些

  for j=3 to activesheet.cells(Rows.count,1).End(xlUp).Row

But the value is not updating i Guess its just checking upto 1000 only its not updating the number of rows value in the to condtion.

但是该值不会更新我猜它只是检查最多 1000 只它不会更新条件中的行数值。

How do I count number of rows and keep it in a condition if rows are created in between?

如果在两者之间创建行,我如何计算行数并将其保持在一个条件中?

回答by Patrick Honorez

Why don't you try looping backwards ? for j = rowZ to 3 step -1.
Might that solve your problem ?

你为什么不尝试向后循环?for j = rowZ to 3 step -1.
这能解决你的问题吗?



Edit: option 2, you could define a name for the cell after the last one, and refer that Named Range: Range("myLastCell"). It will adjust every time you insert rows....

编辑:选项 2,您可以在最后一个之后为单元格定义一个名称,并引用该 Named Range: Range("myLastCell")。每次插入行时它都会调整....

回答by JMax

You might try to loop through a range:

您可能会尝试遍历一个范围:

Sub LoopRange()
   Dim cell As Range, Rowz as Long
   Rowz = Activesheet.Cells(Rows.count,1).End(xlUp).Row
   For Each cell In Range("A1:A" & Rowz)
    'do things
   Next Bcell
End Sub

Warning:the vba will parse the whole range, includingthe inserted rows, so if you insert a row on every loop, your procedure will loop indefinitely (note, you can use Ctrl+Pauseto stop the execution of your code if it happens)

警告:vba 将解析整个范围,包括插入的行,因此如果您在每个循环中插入一行,您的过程将无限循环(注意,如果发生这种情况,您可以使用Ctrl+Pause来停止代码的执行)