简体   繁体   中英

Using Cell property in VBA For Next loop function

Hi i am just starting to learn vba and have a question

Whenever I use the For Next loop function in my VBA code, I always need to create a variable "Cell" or no?

When you use the FOR...NEXT statement, you do need to have a variable to count, as well as a start and an end. However, you don't need to use Cell as the counter.

In Visual Basic, press F1 and type "for" in the search box. This will bring up enough to get you started!

No, you do not have to create a variable for it, you are more than welcome to call the cell directly. Below, let's assume you are checking A1:A10 to see if the cell contains the string "Foo":

For i = 1 To 10
    If Cells(i, 1).Value = "Foo" Then
        'Do something
    End If
Next

Here's how it would look if you made a variable for it:

For i = 1 To 10
    cellValue = Cells(i, 1).Value
    If cellValue = "Foo" Then
        'Do something
    End If
Next

Now, in general you do not need to create a variable to store the value in, especially if you are only using it once or twice because the act of storing the variable negates any speed boost you would get from just referencing the cell directly. Plus as you can see above, there are obvious benifits from calling a cell direclty, for example when loopoing (you can use "Range("A" & i)" or "cells(i, 1)" but the later is faster and better for looping, especially since it does not include any concatenation).

Important Point

That being said, if you are going to refer to the contents of that cell many times in your loop, then it is more effectient to store it in a variable like "cell" and work on that instead of calling up Excel for the value each time. My general rule is that if I refer to the contents of a cell more than 2 times, I store it in a variable.

The other benifit of storing the value in a variable is the ability to set break points easier and pinpoint when something has gone wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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