将特定的整列从文件1复制到2

时间:2017-01-11 08:15:33

标签: excel vba excel-vba

您好我正在尝试使用以下代码将C,R,W,X列从文件1复制到文件2,但不断收到错误。我的VBA知识还不是那么好但可能与范围设置有关吗?我尝试了多种方法,但无法让它发挥作用。

我使用正确的设置还是应该使用其他操作来获取特定列?

Sub PFS()

Dim wbCopy As Workbook
Dim wsCopy As Worksheet
Dim rngCopy As Range
Dim wbPaste As Workbook
Dim wsPaste As Worksheet
Dim rngPaste As Range

Set wbPaste = ActiveWorkbook
Set wbCopy = Workbooks.Open("path to copy")
Set wsCopy = wbCopy.Worksheets("Blad1")
Set rngCopy = wsCopy.Range("d, e").EntireColumn
Set wsPaste = wbPaste.Worksheets("PFS")
Set rngPaste = wsPaste.Range("a1")

rngCopy.Copy
rngPaste.PasteSpecial

Workbooks.Application.CutCopyMode = False

Application.DisplayAlerts = False
wbCopy.Save
wbCopy.Close

End Sub

1 个答案:

答案 0 :(得分:0)

复制整栏的解决方案。

Sub copy()
    Dim wb As Workbook
    Dim wbNew As Workbook
    Dim ws As Worksheet
    Dim wsNew As Worksheet

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("old")
    Set wbNew = Workbooks("Book.xlsx")
    Set wsNew = wbNew.Sheets("new")

    ws.Columns(3).copy
    wsNew.Columns(3).Insert Shift:=xlToRight

    ws.Columns(18).copy
    wsNew.Columns(18).Insert Shift:=xlToRight

    ws.Columns(23).copy
    wsNew.Columns(23).Insert Shift:=xlToRight

    ws.Columns(24).copy
    wsNew.Columns(24).Insert Shift:=xlToRight

    Set wsNew = Nothing
    Set wbNew = Nothing
    Set ws = Nothing
    Set wb = Nothing
End Sub