Excelmacrosselect多个列并将其粘贴到新工作簿的工作表1中

好日子优点,请任何人都可以把我放在正确的方向,我试图在excel表中的列标题select多个列,然后将这些列复制到一个新的工作簿,当我用下面的代码这样做,Excel打开而不是将所有选定的列粘贴到新工作簿的工作表1中。 请帮忙。 (我遇到过不同的解决scheme,我只是没有得到如何让他们为我工作,我想由于缺乏经验,我logging了这个任务运行良好的macros,但问题是,列标题每次更改所以我不能依靠录制的macros)。 谢谢。

Sub Colheadr() Dim wsO As Worksheet 'Dim wsF As Worksheet....I comment out this line Dim i As Integer Application.ScreenUpdating = False Set wsO = ActiveSheet 'Set wsF = Worksheets("Final").....I comment out this line myColumns = Array("Facility", "Last Name", "First Name", "MRN", "adm date") With wsO.Range("A1:W1") For i = 0 To UBound(myColumns) On Error Resume Next .Find(myColumns(i)).EntireColumn.Copy Workbook.Add ActiveSheet.Paste 'Destination:=wsF.Cells(1, i + 1)...I comment out this line Err.Clear Next i End With Set wsO = Nothing Set wsF = Nothing Application.ScreenUpdating = True End Sub 

试试这个:

 Public Sub CopyBetweenBooks() Dim myCollection As Collection Dim myIterator As Variant Dim myRng As Range Dim xlcell As Variant Dim otherwb As Workbook Dim mywb As Workbook Dim colCounter As Integer Set mywb = ThisWorkbook Set myCollection = New Collection 'Create a collection of header names to search through myCollection.Add ("Header1") myCollection.Add ("Header2") myCollection.Add ("Header3") 'Where to search, this is the header Set myRng = ActiveSheet.Range("A1:W1") Set otherwb = Workbooks.Add colCounter = 0 For Each xlcell In myRng.Cells ' look through each cell in your header For Each myIterator In myCollection ' look in each item in the collection If myIterator = xlcell.Value Then ' when the header matches what you are looking for colCounter = colCounter + 1 ' creating a column index for the new workbook mywb.ActiveSheet.Columns(xlcell.Column).Copy otherwb.ActiveSheet.Columns(colCounter).Select otherwb.ActiveSheet.Paste End If Next Next End Sub