0

I have a requirement where I need to select Multiple columns using only the header names and this is my code for that ,

colmz = WorksheetFunction.Match("Sheet1", Sheets("Age").Rows(1), 0)
Nrowz = ActiveSheet.Cells(Rows.Count, colmz).End(xlUp).Row
Sheets("sheet1").Range(Cells(1, colmz), Cells(Nrowz, colmz)).Select

colm = WorksheetFunction.Match("Sheet1", Sheets("Gender").Rows(1), 0)
Sheets("sheet1").Range(Cells(1, colm), Cells(Nrowz, colm)).Select

I was able to select them individually but not together. How do I use them inside the range function and select both the columns together. Kindly give me your suggestions. Thanks in advance.

1
  • You can only select one by one so if you use 2 "select", the first one will become useless Commented Mar 3, 2017 at 14:37

2 Answers 2

1

You want to select the UNION of the two ranges. For clarity, I've created ranges for the two areas to .select. Using this method allows you to specify the Sheet to use also.

Dim age_range, gender_range As Range

colmz = WorksheetFunction.Match("Sheet1", Sheets("Age").Rows(1), 0)
Nrowz = ActiveSheet.Cells(Rows.Count, colmz).End(xlUp).Row
colm = WorksheetFunction.Match("Sheet1", Sheets("Gender").Rows(1), 0)

Set age_range = Sheets("sheet1").Range(Cells(1, colmz), Cells(Nrowz, colmz))
Set gender_range = Sheets("sheet1").Range(Cells(1, colm), Cells(Nrowz, colm))

Sheets("sheet1").Range(Union(age_range, gender_range).Address).Select
Sign up to request clarification or add additional context in comments.

Comments

0

I tried the Union function and it did work for me

Union(Range(Cells(1, colmz), Cells(Nrowz, colmz)), Range(Cells(1, colm), Cells(Nrowz, colm))).Select

kindly let me know, if there is a better practice than this

2 Comments

well it depends on different things : Are you doing this only once or you will repeat this code multiple times ? If so, are the columns you want to select always called by those 2 header names or not ?
@Seb I don't have to use it again and again. I only need to use them once. but still, I think I will still go with the Answer provided by CLR

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.