简体   繁体   中英

EXCEL-VBA Change a range with a loop

Set rng = Worksheets("Sheet1").Range("B2")

I have the above and would like to run a loop that changes the range I use/evaluate. I have tried variations of the following.

for x = 2 to 10
Set rng = Worksheets("No-Funding").Range(x & "2")
Next X

I have done some investigating and found this other Stack Overflow: Excel VBA Looping formula to change Range I can not make sense of it in this situation though.

My code will not work if it uses cells either, I have tried that and can only make it work with Range. Thanks for any help provided!

For a strictly numerical increment try,

Set rng = Worksheets("No-Funding").Cells(x, 2)

An xlA1 style reference can be achieved by factoring in the ASCII character.

Set rng = Worksheets("No-Funding").Range(Chr(64 + x) & 2)

Try this:

For x = 2 To 10
    Set rng = Worksheets("No-Funding").Cells(2, x)
Next x

As far as I know it is no matter for VBA if you use function .Range or .Cells , since both of them return object or Range type.

Use

Set rng = Worksheets("Sheet1").Range("B2").Offset(0,x)

to move to a different column. Better yet

Dim values as Variant, rng as Range
Set rng = Worksheets("Sheet1").Range("B2").Resize(10,1)
values = rng.Values2

For i=1 to 10
   values(i,1) = 2*values(i,1)
Next i

rng.Values2 = values

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