简体   繁体   English

使用标题名称选择多个列-Excel VBA

[英]Selecting Multiple Columns Using Header names - Excel VBA

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. 提前致谢。

You want to select the UNION of the two ranges. 您要选择两个范围的UNION For clarity, I've created ranges for the two areas to .select . 为了清楚起见,我为这两个区域创建了.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

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 请告诉我,是否有比这更好的做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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