简体   繁体   English

VBA Excel中-循环的下一行

[英]vba excel - next row for loop

I made a vba code which I want to click on a button (testing1) to check whether range A2 in WS "temp log" is empty, if yes, insert value of range H1 from WS "Main". 我做了一个VBA代码,我想单击一个按钮(testing1),以检查WS“临时日志”中的范围A2是否为空,如果是,则从WS“主”中插入范围H1的值。 however, when i run through my code, it will go to this line. 但是,当我运行我的代码时,它将转到此行。 For r = 2 To .Range("AA65535").End(xlUp).Row

and it will jump to end with (Temp log). 它将end with (Temp log) end with

Could someone explain that why wouldn't the code run through the for loop please? 有人可以解释为什么代码不能通过for循环运行吗?

Sub testing1()

Dim r As Integer    
Dim totalValue As Object

With Worksheets("Main")

     Set totalValue = .Range("H1")

End With

With Worksheets("Temp log")



          For r = 2 To .Range("A65535").End(xlUp).Row

                If IsEmpty(.Cells(r, "A").Value) = True Then

                   .Cells(r, "A").Value = totalValue

                End If

          Next r
end with 

end sub
.Range("A65535").End(xlUp).Row

This will return the row number of the last empty row in the worksheet (for column A). 这将返回工作表中最后一个空行的行号(对于A列)。 If A2 in "Temp Log" is empty and every row above it is empty your FOR loop will look like: 如果“临时日志”中的A2为空,并且其上方的每一行均为空,则FOR循环将如下所示:

For r = 2 to 2

Which will iterate exactly 0 times. 它将精确地迭代0次。

IF A2 is empty AND everything below it is empty, what result do you want? 如果A2为空并且其下面的所有内容为空,您想要什么结果? Fill only A2 with your TotalValue and stop, or keep on filling everything below A2 down to the bottom of the worksheet? 用您的TotalValue仅填充A2并停止,还是继续填充A2之下的所有内容直到工作表的底部?

If your .Range(#).End(xlUp).Row finds nothing in A2 nor anywhere below it, it will return 1 (not 2), and your loop would be 如果您的.Range(#)。End(xlUp).Row在A2或它下面的任何地方都找不到,它将返回1(而不是2),并且您的循环将是

For R = 2 to 1

And that will be skipped. 这将被跳过。 (A loop with For r = 2 to 2 WILL run, once, with r = 2). For r = 2 to 2循环将运行一次,r = 2)。

You may want to define the bottom row, and depending on what you find, either fill A2 with TotalValue and stop, or (if something below A2 IS populated) fill everything empty from A2 down to that last row using the loop as you have. 您可能需要定义底部的行,并根据找到的内容,用TotalValue填充A2并停止,或者(如果填充了A2以下的内容)使用循环使用A2填充所有内容,直到最后一行。

Or if I've missed your intent, please explain further. 或者,如果我错过了您的意图,请进一步说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM