2017-07-28 38 views
0

我嘗試了以下代碼將整個列從一個頁面複製到其他頁面。將常見列複製到單獨的工作表

我有一個共同的標題,是六月分散在工作表中,我只想複製列表,標題名稱爲「六月」在單獨的工作表中一個接一個。

EG如果列A,C,L,M的列標題爲6月,那麼在下一張表中,這些列表只應複製爲A,B,C,D。

Sheets("sheet1").Select 
June = WorksheetFunction.Match("Description", Rows("1:1"), 0) 

Sheets("sheet1").Columns(June).Copy Destination:=Sheets("sheet2").Range("A1") 
+0

使用'Find'函數第1行中,設置了'Range',如果'Find'是成功的,得到了​​'Column'財產 –

回答

1

下面可能有幫助:

Option Explicit 

Sub Demo() 
    Dim srcSht As Worksheet, destSht As Worksheet 
    Dim headerRng As Range, cel As Range, copyRng As Range 
    Dim lastCol As Long, col As Long 

    Set srcSht = ThisWorkbook.Sheets("Sheet1")  'Sheet1 
    Set destSht = ThisWorkbook.Sheets("Sheet2")  'Sheet2 

    lastCol = srcSht.Cells(1, srcSht.Columns.Count).End(xlToLeft).Column 'last column of Sheet1 

    With srcSht 
     For Each cel In .Range(.Cells(1, 1), .Cells(1, lastCol)) 'loop through each header name in Sheet1 
      If cel = "June" Then       'check header is "June" 
       If copyRng Is Nothing Then     'assign range to copy 
        Set copyRng = .Columns(cel.Column) 
       Else 
        Set copyRng = Union(copyRng, .Columns(cel.Column)) 
       End If 
      End If 
     Next cel 
    End With 
    copyRng.Copy destSht.Range("A1")    'copy and paste desired columns 
End Sub 
+1

尼斯+您可以使用'With srcSht'縮短並清理您的代碼 –

+0

它在copyRng.Copy destSht.Range(「A1」)中顯示錯誤。 –

+0

@NehaKohli - 什麼是錯誤? – Mrig

相關問題