简体   繁体   中英

Multiple cell selection in VBA using ActiveCell.Offset(0, 1).Value

I'm starting in VBA and had to do a program that is able to retrieve value from a selected cell which will be used as reference.

Range("Y8,Y9,Y10,Y11").Select 'etc....

Either use

Range(ActiveCell, ActiveCell.Offset(0, 1))

or

ActiveCell.Resize(1, 2)

Then you can use it that way

For Each cell In Range(ActiveCell, ActiveCell.Offset(0, 1))
    Debug.Print cell.Value
Next cell

which is equivalent to

Range(ActiveCell, ActiveCell.Offset(0, 1)).Select ' or ActiveCell.Resize(1, 2).Select
For i = 0 To 1
    Debug.Print ActiveCell.Offset(0, i)
Next i

I know this is kinda late and the OP probably has the solution but I think what he wants can be achieved by using Selection like:

Dim r As Range, c As Range

If TypeOf Selection Is Range Then Set r = Selection Else Exit Sub

For Each c In r
    '/* put the code you want here */
    Debug.Print c.Address
    DebUg.Print c.Offset(0,1).Value
Next

Posting as answer just in case someone stumbled on the same problem/issue/requirement.

I was just trying to figure this out today and came across this post, so I thought I would update it with a link to where I found a simple answer.

I go this from https://excelchamps.com/vba/range-offset/

Range(Range("A1").Offset(1, 1), Range("A1").Offset(5, 2)).Select

So using the OP's desire to use ActiveCell as the starting location and an arbitrary range to select using an Offset, it would look something like this:

Range(ActiveCell.Offset(1, 1), ActiveCell.Offset(5, 2)).Select

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