Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "cells" with "range"

Tags:

excel

vba

I have been searching for this for a while now and I have not been successful.

I am trying to use range with cells command in VBA, and the last row is variable. Moreover, I am not getting consecutive columns.

I have to select range S2:S9 and U2:U9 (as already said, last row can be variable). I know this command works:

Range(Cells(2, 19), Cells(NumberofRows, 19)).select

But I need to select 2 different columns that are not consecutive. I am trying something like this but no success:

Range(Cells(2, 19), Cells(NumLinhas, 19);(Cells(2, 21), Cells(NumLinhas, 21)).Select

Does anyone know how to do it?

like image 448
Luccas Esper Klotz Avatar asked Jul 27 '15 20:07

Luccas Esper Klotz


1 Answers

Another option is to use the Union() Method within VBA.

Union(Range(Cells(2, 19), Cells(NumLinhas, 19)), _
    Range(Cells(2, 21), Cells(NumLinhas, 21))).Select

If you have more ranges you wish to add to the union, you can continue to add ranges to the union like below. This is particularly useful when you incorporate a loop into adding ranges to the union.

Dim rngUnion As Range

Set rngUnion = Union(Range("D1:D2"), Range("H1:H2"))
Set rngUnion = Union(rngUnion, Range("B1:B2"))
Set rngUnion = Union(rngUnion, Range("F1:F2"))
rngUnion.Select
like image 169
luke_t Avatar answered Sep 28 '22 05:09

luke_t