使用宏将excel列从一个电子表格复制到另一个电子表格

时间:2014-07-21 22:24:25

标签: excel-vba vba excel

我想知道是否有人可以通过以下代码帮我解决问题

Sub CopyData()
'
' CopyData Macro
' Copys the raw data to the consolidated report
'
' Keyboard Shortcut: Ctrl+w
'Dim sourceColumn As Range, targetColumn As Range
Dim I As Integer
Dim OldColumn(1 To 7) As String
Dim NewColumn(1 To 7) As String
    OldColumn(1) = "A"
    OldColumn(2) = "O"
    OldColumn(3) = "J"
    OldColumn(4) = "M"
    OldColumn(5) = "N"
    OldColumn(6) = "P"

    NewColumn(1) = "A"
    NewColumn(2) = "B"
    NewColumn(3) = "C"
    NewColumn(4) = "D"
    NewColumn(5) = "E"
    NewColumn(6) = "H"

        For I = 1 To 7
            Set sourceColumn = Workbooks("HalliburtonNAFTA").Worksheets("RawData").Columns(OldColumn(I))
            Set targetColumn = Workbooks("HalliburtonNAFTA").Worksheets("NAFTAReport").Columns(NewColumn(I))
                targetColumn = sourceColumn.Value
                sourceColumn.Copy
                targetColumn.Paste
        Next I

    Application.Goto Reference:="CopyData"
    ActiveWorkbook.Save
End Sub

运行此代码时出现两个错误之一。

  1. 我在set sourceColumn行上出现类型不匹配,因为我正在复制数据而不是单元格中的公式而不是单元格的值

  2. 在tagetColumn.Paste行上我需要一个对象,所以我不确定那里有什么。

  3. 如果有人能提供帮助那就太棒了

    谢谢

1 个答案:

答案 0 :(得分:0)

如何一起摆脱sourceColumn和targetColumn变量 - 我们真的不需要它们:

Sub CopyData()

Dim I As Integer
Dim OldColumn(1 To 7) As String
Dim NewColumn(1 To 7) As String
    OldColumn(1) = "A"
    OldColumn(2) = "O"
    OldColumn(3) = "J"
    OldColumn(4) = "M"
    OldColumn(5) = "N"
    OldColumn(6) = "P"

    NewColumn(1) = "A"
    NewColumn(2) = "B"
    NewColumn(3) = "C"
    NewColumn(4) = "D"
    NewColumn(5) = "E"
    NewColumn(6) = "H"

        For I = 1 To 6
            Worksheets("NAFTAReport").Range(NewColumn(I) & "5:" & NewColumn(I) & Rows.Count).Value = Worksheets("RawData").Range(OldColumn(I) & ":" & OldColumn(I)).Value
        Next I

    Application.Goto Reference:="CopyData"
    ActiveWorkbook.Save
End Sub