复制选择列数据直到第1列中的数据结束

时间:2017-04-02 08:36:54

标签: excel-vba vba excel

我目前正在使用以下代码将粘贴数据从File-“Source”复制到File-“Destination”。它正在选择行,直到数据在Column-1中结束。 但是,目前选择了从 A AE 的所有列,但我希望选择 A,F,K,AA 等列。选择。 我理解“wb.ActiveSheet.Range(”A2:AE“& N).Copy”中的代码需要更改但不确定语法。 谁能帮我这个?提前感谢帮助。

Dim wb As Workbook
Set wb = ActiveWorkbook

Dim N As Long
Dim LastRow As Long
N = Cells(2, 1).End(xlDown).Row
wb.ActiveSheet.Range("A2:AE" & N).Copy

Set y = Workbooks.Open("C:\Desktop\Destination.xlsx")

y.Activate
y.Sheets("Data").Select
y.Sheets("Data").Activate


For Each Cell In y.Sheets("Data").Columns(1).Cells
     If Len(Cell) = 0 Then Cell.Select: Exit For
Next Cell
Selection.PasteSpecial Paste:=xlPasteValues
Application.DisplayAlerts = False
ActiveWorkbook.Close True
Application.DisplayAlerts = True
Application.CutCopyMode = False

1 个答案:

答案 0 :(得分:0)

您可以使用Application.Union组合不同列的范围(从第2行到N)。

此外,您可以只使用y.Sheets("Data").Columns(1).Cells,而不是循环浏览Cell以查找空LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1

我添加了2 With wb.Sheets("Sheet1")来完全限定所有变量,Range嵌套在下面。

<强>代码

Option Explicit

Sub CopyColumns()

Dim wb      As Workbook
Dim Y       As Workbook
Dim N       As Long
Dim LastRow As Long
Dim CopyRng As range

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Set wb = ActiveWorkbook

' you need to specify the sheet, otherwise it will take the Active Sheet
With wb.Sheets("Sheet1") ' <-- modify to your sheet's name
    N = .Cells(.Rows.Count, "A").End(xlUp).Row ' <-- get last row from Column "A", skips blank cells in te middle
    ' set the range to Columns A, F, K, AA
    Set CopyRng = Application.Union(.Range("A2:A" & N), .Range("F2:F" & N), .Range("K2:K" & N), .Range("AA2:AA" & N))
End With

Set Y = Workbooks.Open("C:\Desktop\Destination.xlsx")    
With Y.Sheets("Data")
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 '<-- get first empty row at Column A to paste at
    CopyRng.Copy
    .Range("A" & LastRow).PasteSpecial xlPasteValues
End With    
Y.Close True

Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.CutCopyMode = False

End Sub