简体   繁体   English

使用VBA在Excel中选择大型数据库中的特定列

[英]Selecting specific columns in a large database in Excel Using VBA

I have an excel file, starting from A to GM . 我有一个Excel文件,从A到GM。 In row 3, I have columns headings, as an example, as follows: 在第3行中,以列标题为例,如下所示:

 Sub bar Sub Sim bar Sub IV bar 1 1 0 1 1 0 0 4 1 1 1 0 0 1 1 0 0 1 0 1 1 1 0 1 0 1 0 1 3 0 0 0 0 1 1 0 1 1 1 1 0 0 0 0 0 0 1 1 0 0 0 1 1 0 1 1 1 0 0 1 1 1 0 1 1 1 1 1 1 0 0 1 1 0 0 1 0 1 0 1 1 4 0 0 1 1 0 0 

I have several column heading ( sub, bar, sim,...) I want to select the columns with a specific heading column, say "bar" and see them in sheet 2 as follows: 我有几个列标题(sub,bar,sim ...),我想选择具有特定标题列的列,说“ bar”,并在表2中看到它们,如下所示:

 bar bar bar 1 1 4 1 0 0 1 1 1 1 3 0 1 1 1 0 0 1 0 1 1 0 1 1 1 1 1 0 0 1 4 1 0 

I know how to do it using vlookup and filter. 我知道如何使用vlookup和filter做到这一点。 However, I want to do using a simple VBA, if it is possible. 但是,如果可能的话,我想使用一个简单的VBA。 Is it possible? 可能吗?

you could try this: 您可以尝试以下方法:

Sub main()
    Worksheets("Sheet1").Range("A3").CurrentRegion.Copy Destination:=Worksheets("Sheet2").Range("A3") 'copy data from sheet1 to sheet2

    With Worksheets("Sheet2").Range("A3:GM3") 'reference sheet2 headings
        .Replace what:="bar", lookat:=xlWhole, replacement:="" ' replace wanted heading with blank
        .SpecialCells(xlCellTypeBlanks).EntireColumn.Hidden = True ' hide blank headings columns
        .SpecialCells(xlCellTypeVisible).EntireColumn.Delete ' delete visible heading columns
        .EntireColumn.Hidden = False ' unhide hidden columns
        .Value = "bar" 'write wanted heading back
    End With
End Sub

just change "Sheet1" and "Sheet2" to your actual sheet names 只需将“ Sheet1”和“ Sheet2”更改为实际的工作表名称

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

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