在VBA中复制和粘贴特定列

时间:2014-07-04 09:08:51

标签: excel vba

我想在一张纸上复制列(A,C,D,Q:T)并将它们粘贴到另一张纸上。

当我粘贴B列时,也粘贴到另一张纸上。我没有选择B.

这是我的代码:

Private Sub cmdselectfile_Click()
    Dim Filepath As Variant
    Dim ws As Worksheet
    Dim wb As Workbook

    Filepath = Application.GetOpenFilename(FileFilter:="Excel Files, *.xls, All files (*.*), *.*", Title:="Please select a file...")
    If VarType(Filepath) = vbString And Filepath <> Empty Then
        Set wb = Workbooks.Open(Filepath)       'active file
        Union(Columns("A:A"), Columns("C:D"), Columns("Q:T")).Select
        Selection.Copy
        wb.Close
        With ThisWorkbook
             Set ws = ThisWorkbook.Worksheets("data")
             ws.Columns("A:G").PasteSpecial
        End With
        Exit Sub
    Else
        MsgBox "Incorrect Input, Please select the file again"
        Exit Sub
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

您好试试这段代码......

Private Sub cmdselectfile_Click()
    Dim Filepath As Variant
    Dim ws As Worksheet
    Dim wb As Workbook

    Filepath = Application.GetOpenFilename(FileFilter:="Excel Files, *.xls, All files (*.*), *.*", Title:="Please select a file...")
    If VarType(Filepath) = vbString And Filepath <> Empty Then
        Set wb = Workbooks.Open(Filepath)       'active file
        Union(Range("A1").EntireColumn, Range("C1:D1").EntireColumn, Range("Q1:T1").EntireColumn).Copy Destination:=ThisWorkbook.Sheets("data").Range("A1")
        wb.Close
        Exit Sub
    Else
        MsgBox "Incorrect Input, Please select the file again"
        Exit Sub
    End If
End Sub